Add monthly spend reads for custom model providers (#65168)

## What changed

Add an optional `usage_url` to model provider configuration and carry it
through remote thread configuration. Expose `read_provider_usage` to
fetch the current user's monthly USD spend, optional cap and percentage
used, and reset time.

Use the provider's own credentials for the request. Reject redirects,
disable interactive gateway login, and enforce same-origin validation
for gateway OAuth configurations that require it.

## Testing

Cover capped and uncapped spend, percentage rounding, and malformed
responses. Verify usage URL validation and remote configuration
round-tripping.

GitOrigin-RevId: ed805a756aab6e55c24751f0285bfe73b9091f07
This commit is contained in:
alexsong-oai
2026-12-02 04:59:30 +00:00
committed by copyberry
parent 350d8a47c4
commit badc482b81
23 changed files with 452 additions and 11 deletions
+3
View File
@@ -8,6 +8,7 @@ pub(crate) mod responses_websocket;
mod responses_websocket_probe;
pub(crate) mod search;
mod session;
pub(crate) mod usage;
pub use images::ImageRequestError;
pub use images::ImagesClient;
@@ -35,3 +36,5 @@ pub use responses_websocket_probe::ResponsesWebsocketProbe;
pub use responses_websocket_probe::ResponsesWebsocketProbeError;
pub use responses_websocket_probe::ResponsesWebsocketProbeFailureStage;
pub use search::SearchClient;
pub use usage::CurrentUserSpend;
pub use usage::get_current_user_usage;
+149
View File
@@ -0,0 +1,149 @@
//! Read a single UTC monthly spend period from the configured provider.
use crate::auth::SharedAuthProvider;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use codex_client::HttpTransport;
use http::HeaderMap;
use http::Method;
use serde::Deserialize;
const USAGE_RESPONSE_LIMIT: usize = 64 * 1024;
const NANOS_PER_USD: u128 = 1_000_000_000;
#[derive(Debug, PartialEq, Eq)]
pub struct CurrentUserSpend {
pub used_usd: String,
pub limit_usd: Option<String>,
pub used_percent: Option<i32>,
pub reached: bool,
pub period_start: i64,
pub resets_at: i64,
}
#[derive(Deserialize)]
struct UsageResponse {
reached: bool,
usage_periods: [UsagePeriod; 1],
}
#[derive(Deserialize)]
struct UsagePeriod {
period: Period,
period_start: i64,
period_end: i64,
current_usage_amount: Amount,
// Only an explicit null means uncapped.
#[serde(deserialize_with = "Option::deserialize")]
effective_usage_limit: Option<Amount>,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Period {
Month,
}
#[derive(Deserialize)]
struct Amount {
amount: String,
unit: Unit,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Unit {
Usd,
}
fn parse_usd_nanos(value: &str) -> Option<u128> {
let (whole, fraction) = value.split_once('.')?;
if whole.is_empty()
|| !whole.bytes().all(|b| b.is_ascii_digit())
|| !(2..=9).contains(&fraction.len())
|| !fraction.bytes().all(|b| b.is_ascii_digit())
{
return None;
}
// Bounding whole dollars to u64 leaves room for both scaling and percentages in u128.
let whole = whole.parse::<u64>().ok()?;
let fraction_nanos = fraction.parse::<u128>().ok()? * 10_u128.pow(9 - fraction.len() as u32);
Some(u128::from(whole) * NANOS_PER_USD + fraction_nanos)
}
fn decode_usage(body: &[u8]) -> Option<CurrentUserSpend> {
let UsageResponse {
reached,
usage_periods: [period],
} = serde_json::from_slice(body).ok()?;
let UsagePeriod {
period: Period::Month,
period_start,
period_end,
current_usage_amount:
Amount {
amount: used_usd,
unit: Unit::Usd,
},
effective_usage_limit,
} = period;
if period_end <= period_start || period_end.checked_sub(period_start).is_none() {
return None;
}
let used = parse_usd_nanos(&used_usd)?;
let limit_usd = effective_usage_limit.map(|amount| amount.amount);
let used_percent = match &limit_usd {
Some(amount) => {
let limit = parse_usd_nanos(amount)?;
Some(if used >= limit {
100
} else {
// Match the ChatGPT backend's ties-to-even rounding at exact half percents.
let scaled = used * 100;
let percent = scaled / limit;
let twice_remainder = (scaled % limit) * 2;
let round_up = twice_remainder > limit
|| (twice_remainder == limit && !percent.is_multiple_of(2));
(percent + u128::from(round_up)) as i32
})
}
None => None,
};
Some(CurrentUserSpend {
used_usd,
limit_usd,
used_percent,
reached,
period_start,
resets_at: period_end,
})
}
pub async fn get_current_user_usage(
transport: impl HttpTransport,
provider: Provider,
auth: SharedAuthProvider,
request_url: String,
) -> Result<CurrentUserSpend, ApiError> {
let session = EndpointSession::new(transport, provider, auth);
let response = session
.execute_with(
Method::GET,
"usage/me",
HeaderMap::new(),
/*body*/ None,
|request| {
request.url.clone_from(&request_url);
request.response_body_limit_bytes = Some(USAGE_RESPONSE_LIMIT);
},
)
.await?;
decode_usage(&response.body).ok_or_else(|| ApiError::InvalidRequest {
message: "Invalid monthly usage response from the gateway".into(),
})
}
#[cfg(test)]
#[path = "usage_tests.rs"]
mod tests;
@@ -0,0 +1,102 @@
#![cfg(test)]
use super::CurrentUserSpend;
use super::decode_usage;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
fn usage(used: &str, limit: Option<&str>, reached: bool) -> Value {
json!({
"reached": reached,
"usage_periods": [{
"period": "month",
"period_start": 1793491200,
"period_end": 1796083200,
"current_usage_amount": {"amount": used, "unit": "usd"},
"effective_usage_limit": limit.map(|amount| json!({"amount": amount, "unit": "usd"})),
}],
})
}
#[test]
fn monthly_usage_preserves_dollars_and_handles_capped_and_uncapped_spend() {
for (used, limit, reached, percent) in [
("78.42", Some("100.00"), false, Some(78)),
("74.60", Some("100.00"), false, Some(75)),
("8.95", Some("10.00"), false, Some(90)),
("8.85", Some("10.00"), false, Some(88)),
("8.949999999", Some("10.00"), false, Some(89)),
("1.00", Some("8.00"), false, Some(12)),
("3.00", Some("8.00"), false, Some(38)),
("0.000000099", Some("0.000000100"), false, Some(99)),
("99.999999999", Some("100.00"), false, Some(100)),
(
"18446744073709551615.999999998",
Some("18446744073709551615.999999999"),
false,
Some(100),
),
("0.00", Some("0.00"), true, Some(100)),
("101.99", Some("100.00"), true, Some(100)),
("70.00", None, false, None),
] {
let body = usage(used, limit, reached);
assert_eq!(
decode_usage(&serde_json::to_vec(&body).unwrap()),
Some(CurrentUserSpend {
used_usd: used.into(),
limit_usd: limit.map(str::to_owned),
used_percent: percent,
reached,
period_start: 1793491200,
resets_at: 1796083200,
})
);
}
}
#[test]
fn malformed_periods_units_and_amounts_do_not_become_uncapped_usage() {
let sample = usage("1.00", Some("20.00"), /*reached*/ false);
for (pointer, bad) in [
("/usage_periods", json!([])),
("/usage_periods/0/period", json!("day")),
("/usage_periods/0/period_end", json!(0)),
(
"/usage_periods/0/current_usage_amount/unit",
json!("credits"),
),
(
"/usage_periods/0/current_usage_amount/amount",
json!("-1.00"),
),
("/usage_periods/0/current_usage_amount/amount", json!("1.0")),
(
"/usage_periods/0/current_usage_amount/amount",
json!("1.0000000000"),
),
(
"/usage_periods/0/effective_usage_limit/amount",
json!("1.00e2"),
),
(
"/usage_periods/0/effective_usage_limit/amount",
json!("18446744073709551616.00"),
),
(
"/usage_periods/0/effective_usage_limit/amount",
json!("NaN"),
),
] {
let mut value = sample.clone();
*value.pointer_mut(pointer).unwrap() = bad;
assert_eq!(decode_usage(&serde_json::to_vec(&value).unwrap()), None);
}
let mut missing = sample;
missing["usage_periods"][0]
.as_object_mut()
.unwrap()
.remove("effective_usage_limit");
assert_eq!(decode_usage(&serde_json::to_vec(&missing).unwrap()), None);
}
+2
View File
@@ -61,6 +61,7 @@ pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
pub use crate::common::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY;
pub use crate::common::create_text_param_for_request;
pub use crate::common::response_create_client_metadata;
pub use crate::endpoint::CurrentUserSpend;
pub use crate::endpoint::ImageRequestError;
pub use crate::endpoint::ImagesClient;
pub use crate::endpoint::MemoriesClient;
@@ -86,6 +87,7 @@ pub use crate::endpoint::ResponsesWebsocketProbe;
pub use crate::endpoint::ResponsesWebsocketProbeError;
pub use crate::endpoint::ResponsesWebsocketProbeFailureStage;
pub use crate::endpoint::SearchClient;
pub use crate::endpoint::get_current_user_usage;
pub use crate::endpoint::session_update_session_json;
pub use crate::error::ApiError;
pub use crate::files::HostedFileUploadContext;