use cpa_core::credential::Credential;
use cpa_core::exec::{CaptureEvent, CaptureSink, UpstreamRequest};
use http::HeaderMap;
pub(crate) fn http_pairs(headers: &HeaderMap) -> Vec<(String, String)> {
headers
.iter()
.map(|(name, value)| {
(
crate::proxy::canonical_header(name.as_str()),
String::from_utf8_lossy(value.as_bytes()).into_owned(),
)
})
.collect()
}
fn websocket_pairs(headers: &HeaderMap) -> Vec<(String, String)> {
headers
.iter()
.map(|(name, value)| {
let name = match name.as_str() {
"session_id" => "session_id".to_owned(),
"chatgpt-account-id" => "ChatGPT-Account-ID".to_owned(),
other => crate::proxy::canonical_header(other),
};
(name, String::from_utf8_lossy(value.as_bytes()).into_owned())
})
.collect()
}
fn upgrade_url(url: &str) -> String {
let url = url.trim();
match url.split_once("://") {
Some((scheme, rest)) if scheme.eq_ignore_ascii_case("ws") => format!("http://{rest}"),
Some((scheme, rest)) if scheme.eq_ignore_ascii_case("wss") => format!("https://{rest}"),
_ => url.to_owned(),
}
}
#[derive(Clone, Default)]
pub(crate) struct Wire {
sink: CaptureSink,
websocket: Option<cpa_core::exec::WebSocketEmitter>,
auth_id: String,
auth_label: String,
auth_type: &'static str,
auth_value: String,
}
impl Wire {
pub(crate) fn new(sink: &CaptureSink, credential: &Credential) -> Self {
if !sink.enabled() {
return Self::default();
}
let (auth_type, auth_value) = cpa_core::registry::dynamic::account_info(credential);
Self {
sink: sink.clone(),
websocket: None,
auth_id: credential.id.clone(),
auth_label: credential.label.clone(),
auth_type,
auth_value,
}
}
pub(crate) fn with_websocket(mut self, websocket: Option<cpa_core::exec::WebSocketEmitter>) -> Self {
self.websocket = websocket;
self
}
pub(crate) fn enabled(&self) -> bool {
self.sink.enabled()
}
fn info<'a>(
&'a self,
url: &'a str,
method: &'a str,
headers: &'a [(String, String)],
body: &'a [u8],
) -> UpstreamRequest<'a> {
UpstreamRequest {
url,
method,
headers,
body,
provider: "codex",
auth_id: &self.auth_id,
auth_label: &self.auth_label,
auth_type: self.auth_type,
auth_value: &self.auth_value,
}
}
pub(crate) fn request(&self, url: &str, headers: &HeaderMap, body: &[u8]) {
if self.enabled() {
let headers = http_pairs(headers);
self.sink
.record(CaptureEvent::Request(self.info(url, "POST", &headers, body)));
}
}
pub(crate) fn metadata(&self, status: u16, headers: &HeaderMap) {
if self.enabled() {
let headers = http_pairs(headers);
self.sink.record(CaptureEvent::ResponseMetadata(status, &headers));
}
}
pub(crate) fn chunk(&self, bytes: &[u8]) {
self.sink.record(CaptureEvent::ResponseChunk(bytes));
}
pub(crate) fn error(&self, text: &str) {
self.sink.record(CaptureEvent::ResponseError(text));
}
pub(crate) fn exec_error(&self, error: &cpa_core::exec::ExecError) {
if self.enabled() {
self.error(&String::from_utf8_lossy(&error.body));
}
}
pub(crate) fn ws_request(&self, url: &str, headers: &HeaderMap, body: &[u8]) {
if self.enabled() {
let headers = websocket_pairs(headers);
self.sink.record(CaptureEvent::WebsocketRequest(self.info(
url,
"WEBSOCKET",
&headers,
body,
)));
}
}
pub(crate) fn ws_frame(&self, url: &str, body: &[u8]) {
if self.enabled() {
self.sink.record(CaptureEvent::WebsocketRequest(UpstreamRequest {
url,
method: "WEBSOCKET",
headers: &[],
body,
provider: "codex",
auth_id: &self.auth_id,
auth_label: "",
auth_type: "",
auth_value: "",
}));
}
}
pub(crate) fn ws_handshake(&self, status: u16, headers: &HeaderMap) {
if self.enabled() {
let headers = http_pairs(headers);
self.sink.record(CaptureEvent::WebsocketHandshake(status, &headers));
}
}
pub(crate) fn ws_response_observation(
&self,
payload: &str,
) -> Option<futures_util::future::BoxFuture<'static, ()>> {
self.sink.record(CaptureEvent::WebsocketResponse(payload.as_bytes()));
let websocket = self.websocket.clone()?;
let payload = payload.to_owned();
Some(Box::pin(async move { websocket.emit(payload.as_bytes()).await }))
}
pub(crate) fn ws_error(&self, stage: &str, error: &str) {
self.sink.record(CaptureEvent::WebsocketError { stage, error });
}
pub(crate) fn ws_exec_error(&self, stage: &str, error: &cpa_core::exec::ExecError) {
if self.enabled() {
self.ws_error(stage, &String::from_utf8_lossy(&error.body));
}
}
pub(crate) fn upgrade_rejection(
&self,
ws_url: &str,
request: &HeaderMap,
status: u16,
headers: &HeaderMap,
body: &[u8],
) {
if !self.enabled() {
return;
}
let mut pairs = websocket_pairs(request);
for (name, value) in [("Connection", "Upgrade"), ("Upgrade", "websocket")] {
let present = request
.get(name)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| !v.trim().is_empty());
if !present {
pairs.retain(|(n, _)| n != name);
pairs.push((name.to_owned(), value.to_owned()));
}
}
let url = upgrade_url(ws_url);
self.sink
.record(CaptureEvent::Request(self.info(&url, "GET", &pairs, &[])));
self.metadata(status, headers);
self.chunk(body);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upgrade_url_maps_websocket_schemes() {
assert_eq!(upgrade_url("wss://host/v1/responses"), "https://host/v1/responses");
assert_eq!(upgrade_url("WS://host/x"), "http://host/x");
assert_eq!(upgrade_url("https://host"), "https://host");
}
}