mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Route Statsig requests through Codex's HTTP client (#63438)
## Why Statsig requests need to honor the caller's proxy, TLS, and network policy settings. ## What changed Add a `codex-statsig` crate that adapts a caller-supplied `RouteAwareClientPool` to the Statsig SDK's HTTP interface. The adapter requests identity encoding, applies the SDK's timeout and optional response body limit, and leaves HTTP status handling and retries to the SDK. ## Testing Mock-server tests cover request forwarding, preservation of HTTP error responses, response size limits, timeout error mapping, and policy denial before a request reaches the server. GitOrigin-RevId: 6e78435f1f93ee272977b2f0058afd8f485cf4e0
This commit is contained in:
Generated
+1
File diff suppressed because one or more lines are too long
Generated
+36
@@ -133,6 +133,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
]
|
||||
@@ -5179,6 +5180,20 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-statsig"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"codex-http-client",
|
||||
"http 1.4.0",
|
||||
"oai-statsig-rust-client",
|
||||
"pretty_assertions",
|
||||
"tokio",
|
||||
"wiremock",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-tcp-tunnel"
|
||||
version = "0.0.0"
|
||||
@@ -11272,6 +11287,27 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6aa2c4e539b869820a2b82e1aef6ff40aa85e65decdd5185e83fb4b1249cd00f"
|
||||
|
||||
[[package]]
|
||||
name = "oai-statsig-rust-client"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5adc8fe6756bcf80f8039f2312efe1a6f268406f1e9647e8e5ed16ef4fcf60d"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
"dashmap",
|
||||
"http 1.4.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oauth2"
|
||||
version = "5.0.0"
|
||||
|
||||
@@ -164,6 +164,7 @@ members = [
|
||||
"codex-client",
|
||||
"codex-api",
|
||||
"state",
|
||||
"statsig",
|
||||
"terminal-detection",
|
||||
"test-binary-support",
|
||||
"thread-manager-sample",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "statsig",
|
||||
crate_name = "codex_statsig",
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "codex-statsig"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
http = { workspace = true }
|
||||
oai-statsig-rust-client = { version = "0.1.0", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
wiremock = { workspace = true }
|
||||
@@ -0,0 +1,121 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use http::Request;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use statsig_client::HttpClient;
|
||||
use statsig_client::NetworkOptions;
|
||||
use statsig_client::StatsigError;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_bytes;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
use super::StatsigHttpClient;
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_http_errors_and_bounds_decoded_responses() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
let client = StatsigHttpClient::new(RouteAwareClientPool::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
ClientRouteClass::Api,
|
||||
));
|
||||
let request_body = br#"{"user":{"userID":"test-user"}}"#;
|
||||
let expected_body = vec![b'x'; 128];
|
||||
let size = expected_body.len();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/initialize"))
|
||||
.and(query_param("k", "client-key"))
|
||||
.and(header("content-type", "application/json"))
|
||||
.and(header("accept-encoding", "identity"))
|
||||
.and(body_bytes(request_body.as_slice()))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(503)
|
||||
.set_body_bytes(expected_body.clone())
|
||||
.insert_header("x-statsig-region", "us"),
|
||||
)
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let request = Request::post(format!("{}/initialize?k=client-key", server.uri()))
|
||||
.header("content-type", "application/json")
|
||||
.body(Bytes::from_static(request_body))?;
|
||||
let send = |limit| {
|
||||
client.send(
|
||||
request.clone(),
|
||||
NetworkOptions {
|
||||
response_body_byte_limit: Some(limit),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
};
|
||||
let response = send(size).await?;
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(response.headers()["x-statsig-region"], "us");
|
||||
assert_eq!(response.body().as_ref(), expected_body.as_slice());
|
||||
assert!(matches!(
|
||||
send(size - 1).await,
|
||||
Err(StatsigError::NetworkResponseTooLarge { limit, actual })
|
||||
if limit == size - 1 && actual == size
|
||||
));
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn honors_the_supplied_network_policy() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
let controller = NetworkPolicyController::default();
|
||||
let client = StatsigHttpClient::new(RouteAwareClientPool::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy()),
|
||||
ClientRouteClass::Api,
|
||||
));
|
||||
let request = Request::get(format!("{}/?key=secret", server.uri())).body(Bytes::new())?;
|
||||
let error = client
|
||||
.send(request, NetworkOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, StatsigError::Network(_)));
|
||||
assert!(!error.to_string().contains("secret"));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_timeout_errors() -> anyhow::Result<()> {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(/* secs */ 1)))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = StatsigHttpClient::new(RouteAwareClientPool::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
ClientRouteClass::Api,
|
||||
));
|
||||
let timeout = Duration::from_millis(/* millis */ 25);
|
||||
let request = Request::get(server.uri()).body(Bytes::new())?;
|
||||
let result = client
|
||||
.send(
|
||||
request,
|
||||
NetworkOptions {
|
||||
timeout,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(result, Err(StatsigError::NetworkTimeout(actual)) if actual == timeout));
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Statsig HTTP requests use the caller's Codex routing and network policy.
|
||||
//! Decoded responses are bounded; status handling and retries stay in the SDK.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use bytes::BytesMut;
|
||||
use codex_http_client::HttpError;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use http::HeaderValue;
|
||||
use http::Request;
|
||||
use http::header::ACCEPT_ENCODING;
|
||||
use http::header::CONTENT_ENCODING;
|
||||
use statsig_client::HttpClient;
|
||||
use statsig_client::HttpClientFuture;
|
||||
use statsig_client::NetworkOptions;
|
||||
use statsig_client::StatsigError;
|
||||
|
||||
/// Sends Statsig traffic through an existing, configured Codex HTTP pool.
|
||||
#[derive(Debug)]
|
||||
pub struct StatsigHttpClient {
|
||||
client: RouteAwareClientPool,
|
||||
}
|
||||
|
||||
impl StatsigHttpClient {
|
||||
/// Reuses the pool's existing proxy, TLS, and network-policy configuration.
|
||||
pub fn new(client: RouteAwareClientPool) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpClient for StatsigHttpClient {
|
||||
fn send(&self, request: Request<Bytes>, options: NetworkOptions) -> HttpClientFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let (mut parts, body) = request.into_parts();
|
||||
parts
|
||||
.headers
|
||||
.insert(ACCEPT_ENCODING, HeaderValue::from_static("identity"));
|
||||
let mut response = self
|
||||
.client
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.version(parts.version)
|
||||
.headers(parts.headers)
|
||||
.body(body)
|
||||
.timeout(options.timeout)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| map_error(error, options.timeout))?;
|
||||
if response
|
||||
.headers()
|
||||
.get_all(CONTENT_ENCODING)
|
||||
.iter()
|
||||
.any(|encoding| !encoding.as_bytes().eq_ignore_ascii_case(b"identity"))
|
||||
{
|
||||
return Err(StatsigError::Network(
|
||||
"unexpected Statsig response encoding".into(),
|
||||
));
|
||||
}
|
||||
let mut bytes = BytesMut::new();
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.map_err(|error| map_error(error, options.timeout))?
|
||||
{
|
||||
let actual = bytes.len().saturating_add(chunk.len());
|
||||
if let Some(limit) = options.response_body_byte_limit
|
||||
&& actual > limit
|
||||
{
|
||||
return Err(StatsigError::NetworkResponseTooLarge { limit, actual });
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
let final_url = response.url().clone();
|
||||
let mut response = response.into_http_response().map(|_| bytes.freeze());
|
||||
response.extensions_mut().insert(final_url);
|
||||
Ok(response)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn map_error(error: HttpError, timeout: Duration) -> StatsigError {
|
||||
if error.is_timeout() {
|
||||
StatsigError::NetworkTimeout(timeout)
|
||||
} else {
|
||||
StatsigError::Network(error.without_url().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "http_client_tests.rs"]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user