mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-23 16:00:40 +00:00
fix(openai): respect response exclusions when reusing WebSockets (#768)
Co-authored-by: Zyy <zyycn@users.noreply.github.com> Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -374,8 +374,13 @@ impl CodexBackendClient {
|
||||
connection_profile.push_str("\0peer:");
|
||||
connection_profile.push_str(&hex::encode(Sha256::digest(route.as_bytes())));
|
||||
}
|
||||
let pool_key =
|
||||
self.websocket_pool_key(request, context, pool_account_id, &connection_profile);
|
||||
let pool_key = self.websocket_pool_key(
|
||||
request,
|
||||
context,
|
||||
pool_account_id,
|
||||
&connection_profile,
|
||||
opening.connection.headers(),
|
||||
);
|
||||
let pool_log_context = pool_key.as_ref().map(WebSocketPoolLogContext::from_key);
|
||||
let downstream_cancellation = context.response_control.and_then(
|
||||
gateway_core::engine::response_control::ResponseControl::connection_cancellation,
|
||||
@@ -702,6 +707,7 @@ impl CodexBackendClient {
|
||||
context: CodexRequestContext<'_>,
|
||||
pool_account_id: Option<&str>,
|
||||
connection_profile: &str,
|
||||
opening_headers: &[(String, String)],
|
||||
) -> Option<CodexWebSocketPoolKey> {
|
||||
let account_id = pool_account_id.or(context.account_id)?;
|
||||
let conversation_id = request
|
||||
@@ -712,6 +718,7 @@ impl CodexBackendClient {
|
||||
.with_egress_key(&self.egress_key)
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_connection_profile(connection_profile)
|
||||
.with_response_exclusions(opening_headers)
|
||||
.with_fedramp_routing(self.fedramp_routing)
|
||||
.with_installation_id(context.installation_id);
|
||||
key = key.with_routing_affinity(self.routing_affinity.as_ref().map(|pin| pin.id()));
|
||||
|
||||
@@ -24,6 +24,7 @@ pub struct CodexWebSocketPoolKey {
|
||||
account_id: String,
|
||||
conversation_id: String,
|
||||
connection_profile: String,
|
||||
response_exclusions: Vec<String>,
|
||||
installation_id: Option<String>,
|
||||
routing_affinity_id: Option<Uuid>,
|
||||
fedramp_routing: bool,
|
||||
@@ -44,6 +45,7 @@ impl CodexWebSocketPoolKey {
|
||||
account_id: account_id.into(),
|
||||
conversation_id: conversation_id.into(),
|
||||
connection_profile: String::new(),
|
||||
response_exclusions: Vec::new(),
|
||||
installation_id: None,
|
||||
routing_affinity_id: None,
|
||||
fedramp_routing: false,
|
||||
@@ -65,6 +67,16 @@ impl CodexWebSocketPoolKey {
|
||||
self
|
||||
}
|
||||
|
||||
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
||||
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
||||
self.response_exclusions = opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// 隔离同一逻辑会话中由不同下游 WebSocket 驱动的并发响应链
|
||||
pub(crate) fn with_downstream_connection_id(
|
||||
mut self,
|
||||
@@ -111,7 +123,7 @@ impl CodexWebSocketPoolKey {
|
||||
.routing_affinity_id
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_default();
|
||||
short_sha256([
|
||||
let parts = [
|
||||
self.base_url.as_str(),
|
||||
self.account_id.as_str(),
|
||||
self.conversation_id.as_str(),
|
||||
@@ -121,7 +133,12 @@ impl CodexWebSocketPoolKey {
|
||||
self.downstream_connection_id.as_str(),
|
||||
self.egress_key.as_str(),
|
||||
routing_affinity.as_str(),
|
||||
])
|
||||
];
|
||||
short_sha256(
|
||||
parts
|
||||
.into_iter()
|
||||
.chain(self.response_exclusions.iter().map(String::as_str)),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn same_logical_connection(&self, other: &Self) -> bool {
|
||||
@@ -132,6 +149,7 @@ impl CodexWebSocketPoolKey {
|
||||
&& self.egress_key == other.egress_key
|
||||
&& self.routing_affinity_id == other.routing_affinity_id
|
||||
&& self.fedramp_routing == other.fedramp_routing
|
||||
&& self.response_exclusions == other.response_exclusions
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2047,6 +2047,109 @@ async fn codex_backend_client_should_discard_pooled_websocket_after_unknown_resp
|
||||
assert_eq!(accepted_connections.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||
const EXCLUSIONS: &[&[&str]] = &[
|
||||
&[],
|
||||
&["tools,usage.attribution"],
|
||||
&["tools"],
|
||||
&["tools", "usage.attribution"],
|
||||
&[""],
|
||||
];
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let mut handlers = tokio::task::JoinSet::new();
|
||||
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
|
||||
let actual: Vec<_> = request
|
||||
.headers()
|
||||
.get_all("x-codex-exclude")
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
})
|
||||
.await;
|
||||
handlers.spawn(async move {
|
||||
let mut turn = 0;
|
||||
while let Some(Ok(Message::Text(_))) = socket.next().await {
|
||||
let id = format!("resp_{index}_{turn}");
|
||||
socket
|
||||
.send(Message::Text(
|
||||
completed_websocket_response(&id, 1, 1).into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
turn += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(listener);
|
||||
while let Some(result) = handlers.join_next().await {
|
||||
result.unwrap();
|
||||
}
|
||||
});
|
||||
let pool = Arc::new(CodexWebSocketPool::new(Duration::from_mins(1)));
|
||||
let backend = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{addr}"),
|
||||
test_wire_profile(),
|
||||
)
|
||||
.with_websocket_pool(pool.clone());
|
||||
let make_request = |values: &[&str]| {
|
||||
let headers: Vec<_> = values
|
||||
.iter()
|
||||
.map(|&value| ("x-codex-exclude", value))
|
||||
.collect();
|
||||
let mut request = encode_request_with_headers(
|
||||
codex_request_body("gpt-test", "be brief", vec![]),
|
||||
&headers,
|
||||
);
|
||||
request.local_conversation_id = Some("shared-session".into());
|
||||
request.use_websocket = true;
|
||||
request
|
||||
};
|
||||
let context = request_context("req_exclusions", Some("account"));
|
||||
for (index, &values) in EXCLUSIONS.iter().enumerate() {
|
||||
let request = make_request(values);
|
||||
for (turn, expected) in ["new", "reuse"].into_iter().enumerate() {
|
||||
let response = backend.create_response(&request, context).await.unwrap();
|
||||
assert_eq!(
|
||||
response.websocket_pool_decision.unwrap().kind(),
|
||||
expected,
|
||||
"{values:?}"
|
||||
);
|
||||
assert!(response.body.contains(&format!("resp_{index}_{turn}")));
|
||||
}
|
||||
let continue_from_last_response = |mut request: CodexResponsesRequest| {
|
||||
request.set_previous_response_id(Some(format!("resp_{index}_1")));
|
||||
request.previous_response_scope = Some(PreviousResponseScope::ConnectionLocal);
|
||||
request
|
||||
};
|
||||
let changed = make_request(EXCLUSIONS[(index + 1) % EXCLUSIONS.len()]);
|
||||
let error = backend
|
||||
.create_response(&continue_from_last_response(changed), context)
|
||||
.await
|
||||
.expect_err("changed exclusions must require replay");
|
||||
assert!(matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: PreviousResponseUnavailableReason::FreshConnectionRequired,
|
||||
..
|
||||
})
|
||||
));
|
||||
let response = backend
|
||||
.create_response(&continue_from_last_response(request), context)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(response.body.contains(&format!("resp_{index}_2")));
|
||||
}
|
||||
pool.shutdown().await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_header_should_open_a_distinct_websocket() {
|
||||
assert_changed_handshake_opens_distinct_websocket("x-codex-guardian", "reviewer").await;
|
||||
|
||||
Reference in New Issue
Block a user