Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

fix clippy diagnostics

Raine Virtadff2b3697366
diff --git a/src/config.rs b/src/config.rs
index 3f90dca..0d54e5f 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -228,12 +228,11 @@ pub fn kimi_oauth_host() -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(kimi) = file.kimi {
- if let Some(host) = kimi.oauth_host {
- return host;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(kimi) = file.kimi
+ && let Some(host) = kimi.oauth_host
+ {
+ return host;
}
"https://auth.kimi.com".to_string()
}
@@ -244,12 +243,11 @@ pub fn kimi_base_url() -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(kimi) = file.kimi {
- if let Some(url) = kimi.base_url {
- return url;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(kimi) = file.kimi
+ && let Some(url) = kimi.base_url
+ {
+ return url;
}
"https://api.kimi.com/coding/v1".to_string()
}
@@ -263,12 +261,11 @@ pub fn kimi_user_agent(default: &str) -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(kimi) = file.kimi {
- if let Some(ua) = kimi.user_agent {
- return ua;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(kimi) = file.kimi
+ && let Some(ua) = kimi.user_agent
+ {
+ return ua;
}
default.to_string()
}
@@ -286,12 +283,11 @@ pub fn codex_base_url(default: &str) -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- if let Some(url) = codex.base_url {
- return url;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(url) = codex.base_url
+ {
+ return url;
}
default.to_string()
}
@@ -302,12 +298,11 @@ pub fn codex_originator(default: &str) -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- if let Some(val) = codex.originator {
- return val;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(val) = codex.originator
+ {
+ return val;
}
default.to_string()
}
@@ -321,12 +316,11 @@ pub fn codex_user_agent(default: &str) -> String {
return raw.clone();
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- if let Some(ua) = codex.user_agent {
- return ua;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(ua) = codex.user_agent
+ {
+ return ua;
}
default.to_string()
}
@@ -337,12 +331,11 @@ pub fn codex_previous_response_id() -> bool {
return matches!(raw.to_ascii_lowercase().as_str(), "1" | "true" | "yes");
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- if let Some(val) = codex.previous_response_id {
- return val;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(val) = codex.previous_response_id
+ {
+ return val;
}
false
}
@@ -353,10 +346,10 @@ pub fn codex_service_tier() -> Option<String> {
return Some(raw.clone());
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- return codex.service_tier;
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ {
+ return codex.service_tier;
}
None
}
@@ -367,10 +360,10 @@ pub fn codex_effort() -> Option<String> {
return Some(raw.clone());
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- return codex.effort;
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ {
+ return codex.effort;
}
None
}
@@ -381,10 +374,10 @@ pub fn codex_model() -> Option<String> {
return Some(raw.clone());
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- return codex.model;
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ {
+ return codex.model;
}
None
}
@@ -425,12 +418,11 @@ pub fn codex_transport() -> CodexTransport {
return parse_codex_transport(raw).unwrap_or(CodexTransport::Http);
}
let config_dir = paths::config_dir();
- if let Some(file) = read_file_config(&config_dir) {
- if let Some(codex) = file.codex {
- if let Some(transport) = codex.transport.as_deref().and_then(parse_codex_transport) {
- return transport;
- }
- }
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(transport) = codex.transport.as_deref().and_then(parse_codex_transport)
+ {
+ return transport;
}
CodexTransport::Http
}
diff --git a/src/main.rs b/src/main.rs
index ad7a51c..80c3e2c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -69,7 +69,7 @@ fn main() -> Result<()> {
match commands {
Commands::Version => {
println!("claude-code-proxy {}", VERSION);
- return Ok(());
+ Ok(())
}
Commands::Serve { port } => {
let effective_port = port.unwrap_or_else(config::port);
diff --git a/src/paths.rs b/src/paths.rs
index ed0219b..ac81392 100644
--- a/src/paths.rs
+++ b/src/paths.rs
@@ -107,7 +107,8 @@ pub fn provider_legacy_auth_file(provider: &str) -> PathBuf {
}
fn join_with_sep(base: &str, parts: &[&str], win32: bool) -> PathBuf {
- let sep = if win32 { '/' } else { '/' };
+ let sep = '/';
+ let _ = win32;
let mut out = String::new();
for part in std::iter::once(base).chain(parts.iter().copied()) {
if !out.is_empty() && !out.ends_with(sep) {
diff --git a/src/providers/codex/auth/jwt.rs b/src/providers/codex/auth/jwt.rs
index ac94b40..697ffcf 100644
--- a/src/providers/codex/auth/jwt.rs
+++ b/src/providers/codex/auth/jwt.rs
@@ -6,6 +6,7 @@ struct IdTokenClaims {
chatgpt_account_id: Option<String>,
#[serde(default)]
organizations: Option<Vec<OrgClaim>>,
+ #[allow(dead_code)]
#[serde(default)]
email: Option<String>,
#[serde(default)]
@@ -63,12 +64,11 @@ fn extract_account_id_from_claims(claims: &IdTokenClaims) -> Option<String> {
}
pub fn extract_account_id(tokens: &TokenResponse) -> Option<String> {
- if let Some(ref id_token) = tokens.id_token {
- if let Some(claims) = parse_jwt_claims(id_token) {
- if let Some(account_id) = extract_account_id_from_claims(&claims) {
- return Some(account_id);
- }
- }
+ if let Some(ref id_token) = tokens.id_token
+ && let Some(claims) = parse_jwt_claims(id_token)
+ && let Some(account_id) = extract_account_id_from_claims(&claims)
+ {
+ return Some(account_id);
}
let claims = parse_jwt_claims(&tokens.access_token)?;
extract_account_id_from_claims(&claims)
diff --git a/src/providers/codex/client.rs b/src/providers/codex/client.rs
index 4ca3e76..ce2719a 100644
--- a/src/providers/codex/client.rs
+++ b/src/providers/codex/client.rs
@@ -194,9 +194,16 @@ pub struct CodexHttpClient {
auth_manager: CodexAuthManager<crate::auth::FileAuthStore<StoredAuth>>,
base_url: String,
header_timeout_ms: u64,
+ #[allow(dead_code)]
header_timeout_retries: u32,
}
+impl Default for CodexHttpClient {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl CodexHttpClient {
pub fn new() -> Self {
let timeout_ms = 60_000;
@@ -286,7 +293,7 @@ impl CodexHttpClient {
let pool_key = ctx.session_id.as_deref();
let pool_key = continuation
.and_then(|c| c.previous_response_id.as_ref())
- .and_then(|_| pool_key);
+ .and(pool_key);
super::websocket::codex_websocket_request(
&self.base_url,
@@ -309,7 +316,7 @@ impl CodexHttpClient {
let pool_key = ctx.session_id.as_deref();
let pool_key = continuation
.and_then(|c| c.previous_response_id.as_ref())
- .and_then(|_| pool_key);
+ .and(pool_key);
// Try WebSocket first
let ws_result = super::websocket::codex_websocket_request(
diff --git a/src/providers/codex/continuation.rs b/src/providers/codex/continuation.rs
index baf583b..0563ab1 100644
--- a/src/providers/codex/continuation.rs
+++ b/src/providers/codex/continuation.rs
@@ -187,17 +187,17 @@ pub fn clear_continuation(session_id: Option<&str>) {
None => return,
};
let mut guard = STATES.lock().unwrap();
- if let Some(map) = guard.as_mut() {
- if let Some(existing) = map.remove(session_id) {
- let mut bytes_guard = TOTAL_TRANSCRIPT_BYTES.lock().unwrap();
- *bytes_guard = bytes_guard.saturating_sub(existing.transcript_bytes);
- }
+ if let Some(map) = guard.as_mut()
+ && let Some(existing) = map.remove(session_id)
+ {
+ let mut bytes_guard = TOTAL_TRANSCRIPT_BYTES.lock().unwrap();
+ *bytes_guard = bytes_guard.saturating_sub(existing.transcript_bytes);
}
}
pub fn has_continuation_for_tests(session_id: &str) -> bool {
let guard = STATES.lock().unwrap();
- guard.as_ref().map_or(false, |m| m.contains_key(session_id))
+ guard.as_ref().is_some_and(|m| m.contains_key(session_id))
}
pub fn clear_all_continuations_for_tests() {
@@ -232,7 +232,7 @@ fn prompt_signature(body: &ResponsesRequest) -> String {
};
let mut entries: Vec<(&String, &serde_json::Value)> =
obj.iter().filter(|(k, _)| *k != "input").collect();
- entries.sort_by(|(a, _), (b, _)| a.cmp(b));
+ entries.sort_by_key(|(a, _)| *a);
let mut sig = String::from("{");
for (i, (key, val)) in entries.iter().enumerate() {
if i > 0 {
@@ -256,7 +256,7 @@ fn stable_json(value: &serde_json::Value) -> String {
}
serde_json::Value::Object(obj) => {
let mut entries: Vec<(&String, &serde_json::Value)> = obj.iter().collect();
- entries.sort_by(|(a, _), (b, _)| a.cmp(b));
+ entries.sort_by_key(|(a, _)| *a);
let items: Vec<String> = entries
.iter()
.map(|(k, v)| {
@@ -308,11 +308,11 @@ mod tests {
fields.insert("stream".into(), json!(true));
fields.insert("text".into(), json!({"verbosity": "low"}));
fields.insert("parallel_tool_calls".into(), json!(true));
- if let Some(extras) = extra {
- if let Some(obj) = extras.as_object() {
- for (k, v) in obj {
- fields.insert(k.clone(), v.clone());
- }
+ if let Some(extras) = extra
+ && let Some(obj) = extras.as_object()
+ {
+ for (k, v) in obj {
+ fields.insert(k.clone(), v.clone());
}
}
serde_json::from_value(serde_json::Value::Object(fields)).unwrap()
diff --git a/src/providers/codex/count_tokens.rs b/src/providers/codex/count_tokens.rs
index af34591..a8e7d41 100644
--- a/src/providers/codex/count_tokens.rs
+++ b/src/providers/codex/count_tokens.rs
@@ -5,7 +5,6 @@ use super::translate::request::{
/// Approximate token counter for Codex translated requests.
/// Uses a simple monotonic estimator that satisfies Claude Code's
/// compaction logic (needs approximate, not exact counts).
-
pub fn count_translated_tokens(translated: &ResponsesRequest) -> u64 {
let mut total = 0u64;
diff --git a/src/providers/codex/mod.rs b/src/providers/codex/mod.rs
index 7a02af1..db750db 100644
--- a/src/providers/codex/mod.rs
+++ b/src/providers/codex/mod.rs
@@ -33,6 +33,12 @@ use self::translate::stream::translate_stream_bytes;
pub struct CodexProvider;
+impl Default for CodexProvider {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl CodexProvider {
pub fn new() -> Self {
Self
diff --git a/src/providers/codex/request_summary.rs b/src/providers/codex/request_summary.rs
index aa598a5..39906dd 100644
--- a/src/providers/codex/request_summary.rs
+++ b/src/providers/codex/request_summary.rs
@@ -114,7 +114,7 @@ pub fn summarize_codex_request_size(body: &ResponsesRequest) -> CodexRequestSize
}
})
.collect();
- items.sort_by(|a, b| b.json_bytes.cmp(&a.json_bytes));
+ items.sort_by_key(|item| std::cmp::Reverse(item.json_bytes));
items.truncate(5);
items
};
@@ -136,7 +136,7 @@ pub fn summarize_codex_request_size(body: &ResponsesRequest) -> CodexRequestSize
}
})
.collect();
- items.sort_by(|a, b| b.image_url_bytes.cmp(&a.image_url_bytes));
+ items.sort_by_key(|item| std::cmp::Reverse(item.image_url_bytes));
items.truncate(5);
items
};
@@ -158,7 +158,7 @@ pub fn summarize_codex_request_size(body: &ResponsesRequest) -> CodexRequestSize
});
}
}
- items.sort_by(|a, b| b.json_bytes.cmp(&a.json_bytes));
+ items.sort_by_key(|item| std::cmp::Reverse(item.json_bytes));
items.truncate(5);
items
};
diff --git a/src/providers/codex/translate/accumulate.rs b/src/providers/codex/translate/accumulate.rs
index e51a10f..497862f 100644
--- a/src/providers/codex/translate/accumulate.rs
+++ b/src/providers/codex/translate/accumulate.rs
@@ -49,10 +49,10 @@ pub fn accumulate_response(
});
}
ReducerEvent::TextDelta { index, text } => {
- if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
- if let BlockKind::Text { text: t } = &mut block.kind {
- t.push_str(text);
- }
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index)
+ && let BlockKind::Text { text: t } = &mut block.kind
+ {
+ t.push_str(text);
}
deferred_text_parts.push(text.clone());
}
@@ -70,10 +70,10 @@ pub fn accumulate_response(
index,
partial_json,
} => {
- if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
- if let BlockKind::Tool { args, .. } = &mut block.kind {
- args.push_str(partial_json);
- }
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index)
+ && let BlockKind::Tool { args, .. } = &mut block.kind
+ {
+ args.push_str(partial_json);
}
}
ReducerEvent::Finish {
diff --git a/src/providers/codex/translate/reducer.rs b/src/providers/codex/translate/reducer.rs
index f2c6c22..02a0e83 100644
--- a/src/providers/codex/translate/reducer.rs
+++ b/src/providers/codex/translate/reducer.rs
@@ -107,6 +107,7 @@ pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, Upstream
},
Tool {
index: usize,
+ #[allow(dead_code)]
output_index: usize,
call_id: String,
name: String,
@@ -402,12 +403,10 @@ pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, Upstream
};
if let Some(BlockState::Tool { args_accum, .. }) =
blocks_by_output_index.get_mut(&output_index)
+ && let Some(args) = p.get("arguments").and_then(|v| v.as_str())
+ && args_accum.is_empty()
{
- if let Some(args) = p.get("arguments").and_then(|v| v.as_str()) {
- if args_accum.is_empty() {
- *args_accum = args.to_string();
- }
- }
+ *args_accum = args.to_string();
}
continue;
}
@@ -418,24 +417,24 @@ pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, Upstream
let item = p.get("item");
// Handle web search call done
- if let Some(item_val) = item {
- if item_val.get("type").and_then(|v| v.as_str()) == Some("web_search_call") {
- let idx = anthropic_index;
- anthropic_index += 1;
- let result_index = anthropic_index;
- anthropic_index += 1;
- web_search_requests += 1;
- let id_val = item_val.get("id").and_then(|v| v.as_str()).unwrap_or("");
- let id = server_tool_use_id_from_codex_web_search_id(id_val);
- let query = web_search_query(item_val);
- out.push(ReducerEvent::WebSearch {
- index: idx,
- result_index,
- id,
- query,
- });
- continue;
- }
+ if let Some(item_val) = item
+ && item_val.get("type").and_then(|v| v.as_str()) == Some("web_search_call")
+ {
+ let idx = anthropic_index;
+ anthropic_index += 1;
+ let result_index = anthropic_index;
+ anthropic_index += 1;
+ web_search_requests += 1;
+ let id_val = item_val.get("id").and_then(|v| v.as_str()).unwrap_or("");
+ let id = server_tool_use_id_from_codex_web_search_id(id_val);
+ let query = web_search_query(item_val);
+ out.push(ReducerEvent::WebSearch {
+ index: idx,
+ result_index,
+ id,
+ query,
+ });
+ continue;
}
let state = blocks_by_output_index.remove(&output_index);
@@ -584,7 +583,7 @@ fn sanitize_tool_args(name: &str, args: &str) -> String {
let has_empty_pages = obj
.get("pages")
.and_then(|v| v.as_str())
- .map_or(false, |s| s.is_empty());
+ .is_some_and(|s| s.is_empty());
if !has_empty_pages {
return args.to_string();
}
@@ -652,7 +651,7 @@ fn upstream_failure_kind(payload: &serde_json::Value, message: &str) -> Upstream
return UpstreamErrorKind::Overloaded;
}
- if (status.map_or(false, |s| (500..600).contains(&s)))
+ if (status.is_some_and(|s| (500..600).contains(&s)))
|| code == Some("server_error")
|| code == Some("internal_server_error")
|| code == Some("internal_error")
@@ -721,12 +720,12 @@ pub fn map_codex_usage_to_anthropic(
server_tool_use: None,
};
- if let Some(requests) = web_search_requests {
- if requests > 0 {
- result.server_tool_use = Some(WebSearchUsage {
- web_search_requests: requests,
- });
- }
+ if let Some(requests) = web_search_requests
+ && requests > 0
+ {
+ result.server_tool_use = Some(WebSearchUsage {
+ web_search_requests: requests,
+ });
}
result
diff --git a/src/providers/codex/translate/request.rs b/src/providers/codex/translate/request.rs
index 08712a6..4d880b7 100644
--- a/src/providers/codex/translate/request.rs
+++ b/src/providers/codex/translate/request.rs
@@ -292,10 +292,10 @@ pub fn translate_request(
reasoning: None,
};
- if let Some(tools) = tools {
- if !tools.is_empty() {
- out.tools = Some(tools);
- }
+ if let Some(tools) = tools
+ && !tools.is_empty()
+ {
+ out.tools = Some(tools);
}
if let Some(sid) = opts.session_id {
@@ -410,7 +410,7 @@ fn read_tools(req: &MessagesRequest) -> Result<Option<Vec<ResponsesTool>>, anyho
blocked_domains: None,
};
let allowed = tool.get("allowed_domains").and_then(|v| v.as_array());
- if allowed.map_or(false, |a| !a.is_empty()) {
+ if allowed.is_some_and(|a| !a.is_empty()) {
filters.allowed_domains = allowed.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(String::from))
@@ -418,7 +418,7 @@ fn read_tools(req: &MessagesRequest) -> Result<Option<Vec<ResponsesTool>>, anyho
});
}
let blocked = tool.get("blocked_domains").and_then(|v| v.as_array());
- if blocked.map_or(false, |a| !a.is_empty()) {
+ if blocked.is_some_and(|a| !a.is_empty()) {
filters.blocked_domains = blocked.map(|a| {
a.iter()
.filter_map(|v| v.as_str().map(String::from))
@@ -487,11 +487,9 @@ fn map_tool_choice(req: &MessagesRequest) -> Result<Option<ResponsesToolChoice>,
"tool" => {
let name = choice.get("name").and_then(|v| v.as_str()).unwrap_or("");
let tools = req.extra.get("tools").and_then(|v| v.as_array());
- let is_web_search = tools.map_or(false, |t| {
+ let is_web_search = tools.is_some_and(|t| {
t.iter().any(|tool| {
- tool.get("type")
- .and_then(|v| v.as_str())
- .map_or(false, |t| t == "web_search_20250305")
+ (tool.get("type").and_then(|v| v.as_str()) == Some("web_search_20250305"))
&& tool.get("name").and_then(|v| v.as_str()) == Some(name)
})
});
diff --git a/src/providers/codex/translate/stream.rs b/src/providers/codex/translate/stream.rs
index 1329b06..76952ee 100644
--- a/src/providers/codex/translate/stream.rs
+++ b/src/providers/codex/translate/stream.rs
@@ -18,6 +18,7 @@ pub fn translate_stream_bytes(
let mut web_search_events: Vec<ReducerEvent> = Vec::new();
let mut deferred_content_events: Vec<ReducerEvent> = Vec::new();
+ #[allow(dead_code)]
enum OpenBlock {
Text,
Tool { id: String, name: String },
diff --git a/src/providers/codex/translate/web_search_compat.rs b/src/providers/codex/translate/web_search_compat.rs
index 2938b09..eb44df1 100644
--- a/src/providers/codex/translate/web_search_compat.rs
+++ b/src/providers/codex/translate/web_search_compat.rs
@@ -133,7 +133,7 @@ fn clean_title(value: &str) -> String {
let no_markers = value
.trim_start()
.trim_start_matches(|c: char| c == '-' || c == '*' || c == '+' || c.is_ascii_digit())
- .trim_start_matches(|c: char| c == '.' || c == ')' || c == ' ')
+ .trim_start_matches(['.', ')', ' '])
.replace("**", "")
.replace('`', "")
.trim()
diff --git a/src/providers/codex/websocket.rs b/src/providers/codex/websocket.rs
index c523ba8..c28145f 100644
--- a/src/providers/codex/websocket.rs
+++ b/src/providers/codex/websocket.rs
@@ -109,10 +109,10 @@ pub fn invalidate_codex_websocket_pool_key(session_id: &str) {
fn pool_insert(key: String, entry: Arc<PoolEntry>) {
let mut guard = WS_POOL.lock().unwrap();
// Evict oldest if at capacity
- if guard.len() >= MAX_POOL_ENTRIES {
- if let Some(oldest_key) = guard.keys().next().cloned() {
- guard.remove(&oldest_key);
- }
+ if guard.len() >= MAX_POOL_ENTRIES
+ && let Some(oldest_key) = guard.keys().next().cloned()
+ {
+ guard.remove(&oldest_key);
}
// Evict expired entries
let now = now_ms();
@@ -202,10 +202,9 @@ fn is_previous_response_missing(payload: &serde_json::Value) -> bool {
.get("error")
.and_then(|e| e.get("code"))
.and_then(|v| v.as_str())
+ && code == "previous_response_not_found"
{
- if code == "previous_response_not_found" {
- return true;
- }
+ return true;
}
// Case-insensitive message check
if let Some(msg) = payload
@@ -242,6 +241,7 @@ fn extract_retry_after(payload: &serde_json::Value) -> Option<String> {
// Main request function
// ---------------------------------------------------------------------------
+#[allow(clippy::too_many_arguments)]
pub async fn codex_websocket_request(
url: &str,
headers: &HeaderMap,
@@ -288,29 +288,29 @@ pub async fn codex_websocket_request(
// Collect events
let (sse_body, terminal_event) =
- collect_ws_events(&mut *ws_guard, idle_timeout_ms, pool_key).await?;
+ collect_ws_events(&mut ws_guard, idle_timeout_ms, pool_key).await?;
// Record continuation on success
- if let Some(terminal) = &terminal_event {
- if terminal.payload.get("response").is_some() {
- // Record continuation for successful responses
- if let Some(key) = pool_key {
- invalidate_codex_websocket_pool_key(key);
- }
+ if let Some(terminal) = &terminal_event
+ && terminal.payload.get("response").is_some()
+ {
+ // Record continuation for successful responses
+ if let Some(key) = pool_key {
+ invalidate_codex_websocket_pool_key(key);
}
}
// Handle previous response missing
- if let Some(terminal) = &terminal_event {
- if is_previous_response_missing(&terminal.payload) {
- return Err(CodexError {
- status: 0,
- message: "Previous response not found".to_string(),
- detail: Some("previous_response_not_found".to_string()),
- retry_after: None,
- origin: CodexErrorOrigin::WebSocket,
- });
- }
+ if let Some(terminal) = &terminal_event
+ && is_previous_response_missing(&terminal.payload)
+ {
+ return Err(CodexError {
+ status: 0,
+ message: "Previous response not found".to_string(),
+ detail: Some("previous_response_not_found".to_string()),
+ retry_after: None,
+ origin: CodexErrorOrigin::WebSocket,
+ });
}
// Extract status from error events
@@ -365,21 +365,21 @@ pub async fn codex_websocket_request(
})?;
let (sse_body, terminal_event) =
- collect_ws_events(&mut *ws_guard, idle_timeout_ms, pool_key).await?;
+ collect_ws_events(&mut ws_guard, idle_timeout_ms, pool_key).await?;
- if let Some(terminal) = &terminal_event {
- if is_previous_response_missing(&terminal.payload) {
- if let Some(key) = pool_key {
- invalidate_codex_websocket_pool_key(key);
- }
- return Err(CodexError {
- status: 0,
- message: "Previous response not found".to_string(),
- detail: Some("previous_response_not_found".to_string()),
- retry_after: None,
- origin: CodexErrorOrigin::WebSocket,
- });
+ if let Some(terminal) = &terminal_event
+ && is_previous_response_missing(&terminal.payload)
+ {
+ if let Some(key) = pool_key {
+ invalidate_codex_websocket_pool_key(key);
}
+ return Err(CodexError {
+ status: 0,
+ message: "Previous response not found".to_string(),
+ detail: Some("previous_response_not_found".to_string()),
+ retry_after: None,
+ origin: CodexErrorOrigin::WebSocket,
+ });
}
// Pool the connection if we have a key and it was successful
@@ -415,11 +415,11 @@ pub async fn codex_websocket_request(
tc.write_json("022-upstream-websocket-metadata", &meta);
}
- return Ok(CodexResponse {
+ Ok(CodexResponse {
body: sse_body,
status,
headers: vec![],
- });
+ })
}
}
diff --git a/src/providers/kimi/auth/login.rs b/src/providers/kimi/auth/login.rs
index eb4077b..2f05c67 100644
--- a/src/providers/kimi/auth/login.rs
+++ b/src/providers/kimi/auth/login.rs
@@ -115,10 +115,10 @@ fn build_header_map(
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
let mut map = HeaderMap::new();
for (k, v) in headers {
- if let Ok(name) = HeaderName::from_bytes(k.as_bytes()) {
- if let Ok(value) = HeaderValue::from_str(v) {
- map.insert(name, value);
- }
+ if let Ok(name) = HeaderName::from_bytes(k.as_bytes())
+ && let Ok(value) = HeaderValue::from_str(v)
+ {
+ map.insert(name, value);
}
}
map
diff --git a/src/providers/kimi/auth/manager.rs b/src/providers/kimi/auth/manager.rs
index 95b252d..44150b7 100644
--- a/src/providers/kimi/auth/manager.rs
+++ b/src/providers/kimi/auth/manager.rs
@@ -158,7 +158,7 @@ impl<S: AuthStorage<StoredAuth>> KimiAuthManager<S> {
&self,
tokens: &TokenResponse,
) -> Result<StoredAuth, anyhow::Error> {
- let expires = Self::now_ms() + (tokens.expires_in.unwrap_or(900) as u64 * 1000);
+ let expires = Self::now_ms() + (tokens.expires_in.unwrap_or(900) * 1000);
let auth = StoredAuth {
access: tokens.access_token.clone(),
refresh: tokens.refresh_token.clone().unwrap_or_default(),
@@ -186,10 +186,10 @@ fn build_headers_map(
) -> reqwest::header::HeaderMap {
let mut map = reqwest::header::HeaderMap::new();
for (k, v) in headers {
- if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes()) {
- if let Ok(value) = reqwest::header::HeaderValue::from_str(v) {
- map.insert(name, value);
- }
+ if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes())
+ && let Ok(value) = reqwest::header::HeaderValue::from_str(v)
+ {
+ map.insert(name, value);
}
}
map
diff --git a/src/providers/kimi/client.rs b/src/providers/kimi/client.rs
index 089a5ae..011a8ac 100644
--- a/src/providers/kimi/client.rs
+++ b/src/providers/kimi/client.rs
@@ -26,6 +26,12 @@ pub struct KimiHttpClient {
auth_manager: KimiAuthManager<crate::auth::FileAuthStore<StoredAuth>>,
}
+impl Default for KimiHttpClient {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl KimiHttpClient {
pub fn new() -> Self {
Self {
@@ -118,10 +124,10 @@ impl KimiHttpClient {
// Add common headers
for (k, v) in &headers {
- if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes()) {
- if let Ok(value) = reqwest::header::HeaderValue::from_str(v) {
- req_builder = req_builder.header(name, value);
- }
+ if let Ok(name) = reqwest::header::HeaderName::from_bytes(k.as_bytes())
+ && let Ok(value) = reqwest::header::HeaderValue::from_str(v)
+ {
+ req_builder = req_builder.header(name, value);
}
}
diff --git a/src/providers/kimi/count_tokens.rs b/src/providers/kimi/count_tokens.rs
index 92c684e..3543bce 100644
--- a/src/providers/kimi/count_tokens.rs
+++ b/src/providers/kimi/count_tokens.rs
@@ -37,10 +37,10 @@ fn count_system_tokens(system: &serde_json::Value) -> u64 {
serde_json::Value::Array(arr) => {
let mut total = 0u64;
for block in arr {
- if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
- if !text.starts_with("x-anthropic-billing-header:") {
- total += approx_token_count(text);
- }
+ if let Some(text) = block.get("text").and_then(|v| v.as_str())
+ && !text.starts_with("x-anthropic-billing-header:")
+ {
+ total += approx_token_count(text);
}
}
total
@@ -89,7 +89,7 @@ fn count_content_block_tokens(_role: &str, block: &serde_json::Value) -> u64 {
Some("tool_result") => {
let content = block.get("content");
let role = "tool";
- count_message_tokens(role, &content.unwrap_or(&serde_json::Value::Null))
+ count_message_tokens(role, content.unwrap_or(&serde_json::Value::Null))
}
_ => 0,
}
diff --git a/src/providers/kimi/mod.rs b/src/providers/kimi/mod.rs
index ca84fce..1f4db13 100644
--- a/src/providers/kimi/mod.rs
+++ b/src/providers/kimi/mod.rs
@@ -28,6 +28,12 @@ fn now_ms() -> u64 {
pub struct KimiProvider;
+impl Default for KimiProvider {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl KimiProvider {
pub fn new() -> Self {
Self
diff --git a/src/providers/kimi/translate/accumulate.rs b/src/providers/kimi/translate/accumulate.rs
index eaf26b6..db246b4 100644
--- a/src/providers/kimi/translate/accumulate.rs
+++ b/src/providers/kimi/translate/accumulate.rs
@@ -51,10 +51,10 @@ pub fn accumulate_response(
});
}
ReducerEvent::ThinkingDelta { index, text } => {
- if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
- if let BlockKind::Thinking { text: t } = &mut block.kind {
- t.push_str(text);
- }
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index)
+ && let BlockKind::Thinking { text: t } = &mut block.kind
+ {
+ t.push_str(text);
}
}
ReducerEvent::TextStart { index } => {
@@ -66,10 +66,10 @@ pub fn accumulate_response(
});
}
ReducerEvent::TextDelta { index, text } => {
- if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
- if let BlockKind::Text { text: t } = &mut block.kind {
- t.push_str(text);
- }
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index)
+ && let BlockKind::Text { text: t } = &mut block.kind
+ {
+ t.push_str(text);
}
}
ReducerEvent::ToolStart { index, id, name } => {
@@ -86,10 +86,10 @@ pub fn accumulate_response(
index,
partial_json,
} => {
- if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index) {
- if let BlockKind::Tool { args, .. } = &mut block.kind {
- args.push_str(partial_json);
- }
+ if let Some(block) = blocks.iter_mut().rev().find(|b| b.index == *index)
+ && let BlockKind::Tool { args, .. } = &mut block.kind
+ {
+ args.push_str(partial_json);
}
}
ReducerEvent::Finish {
@@ -204,7 +204,7 @@ mod tests {
#[test]
fn accumulate_handles_upstream_error() {
- let upstream = concat!("data: {\"error\":{\"message\":\"upstream failure\"}}\n\n",);
+ let upstream = "data: {\"error\":{\"message\":\"upstream failure\"}}\n\n";
let result = accumulate_response(upstream.as_bytes(), "msg_e", "model");
assert!(result.is_err());
}
diff --git a/src/providers/kimi/translate/reducer.rs b/src/providers/kimi/translate/reducer.rs
index 9043533..89fc449 100644
--- a/src/providers/kimi/translate/reducer.rs
+++ b/src/providers/kimi/translate/reducer.rs
@@ -89,6 +89,7 @@ struct StreamChoice {
#[derive(Debug, Clone, serde::Deserialize)]
struct StreamDelta {
+ #[allow(dead_code)]
#[serde(default)]
role: Option<String>,
#[serde(default)]
@@ -104,6 +105,7 @@ struct StreamToolCall {
index: usize,
#[serde(default)]
id: Option<String>,
+ #[allow(dead_code)]
#[serde(default)]
r#type: Option<String>,
#[serde(default)]
@@ -150,6 +152,7 @@ struct CompletionTokensDetails {
struct StreamError {
#[serde(default)]
message: Option<String>,
+ #[allow(dead_code)]
#[serde(default)]
r#type: Option<String>,
}
@@ -217,93 +220,93 @@ pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, Upstream
};
// Reasoning content
- if let Some(ref reasoning) = delta.reasoning_content {
- if !reasoning.is_empty() {
- if thinking_index.is_none() {
- thinking_index = Some(next_block_index);
- next_block_index += 1;
- out.push(ReducerEvent::ThinkingStart {
- index: thinking_index.unwrap(),
- });
- }
- out.push(ReducerEvent::ThinkingDelta {
+ if let Some(ref reasoning) = delta.reasoning_content
+ && !reasoning.is_empty()
+ {
+ if thinking_index.is_none() {
+ thinking_index = Some(next_block_index);
+ next_block_index += 1;
+ out.push(ReducerEvent::ThinkingStart {
index: thinking_index.unwrap(),
- text: reasoning.clone(),
});
}
+ out.push(ReducerEvent::ThinkingDelta {
+ index: thinking_index.unwrap(),
+ text: reasoning.clone(),
+ });
}
// Content text
- if let Some(ref content) = delta.content {
- if !content.is_empty() {
- // Close thinking before text
- if let Some(ti) = thinking_index.take() {
- out.push(ReducerEvent::ThinkingStop { index: ti });
- }
- if text_index.is_none() {
- text_index = Some(next_block_index);
- next_block_index += 1;
- out.push(ReducerEvent::TextStart {
- index: text_index.unwrap(),
- });
- }
- out.push(ReducerEvent::TextDelta {
+ if let Some(ref content) = delta.content
+ && !content.is_empty()
+ {
+ // Close thinking before text
+ if let Some(ti) = thinking_index.take() {
+ out.push(ReducerEvent::ThinkingStop { index: ti });
+ }
+ if text_index.is_none() {
+ text_index = Some(next_block_index);
+ next_block_index += 1;
+ out.push(ReducerEvent::TextStart {
index: text_index.unwrap(),
- text: content.clone(),
});
}
+ out.push(ReducerEvent::TextDelta {
+ index: text_index.unwrap(),
+ text: content.clone(),
+ });
}
// Tool calls
- if let Some(ref tool_calls) = delta.tool_calls {
- if !tool_calls.is_empty() {
- // Close thinking and text before tools
- if let Some(ti) = thinking_index.take() {
- out.push(ReducerEvent::ThinkingStop { index: ti });
- }
- if let Some(ti) = text_index.take() {
- out.push(ReducerEvent::TextStop { index: ti });
- }
+ if let Some(ref tool_calls) = delta.tool_calls
+ && !tool_calls.is_empty()
+ {
+ // Close thinking and text before tools
+ if let Some(ti) = thinking_index.take() {
+ out.push(ReducerEvent::ThinkingStop { index: ti });
+ }
+ if let Some(ti) = text_index.take() {
+ out.push(ReducerEvent::TextStop { index: ti });
+ }
- for tc in tool_calls {
- let existing_pos = tool_slots.iter().position(|s| s.block_index == tc.index);
- let block_index = if let Some(pos) = existing_pos {
- tool_slots[pos].block_index
- } else {
- let id = tc.id.clone().unwrap_or_default();
- let name = tc
- .function
- .as_ref()
- .and_then(|f| f.name.clone())
- .unwrap_or_default();
- if id.is_empty() || name.is_empty() {
- // Defensive: skip out-of-order fragments
- continue;
- }
- saw_tool_calls = true;
- let bi = next_block_index;
- next_block_index += 1;
- tool_slots.push(ToolSlot {
- block_index: bi,
- id: id.clone(),
- name: name.clone(),
- });
- out.push(ReducerEvent::ToolStart {
- index: bi,
- id,
- name,
- });
- bi
- };
-
- if let Some(args) = tc.function.as_ref().and_then(|f| f.arguments.as_ref()) {
- if !args.is_empty() {
- out.push(ReducerEvent::ToolDelta {
- index: block_index,
- partial_json: args.to_string(),
- });
- }
+ for tc in tool_calls {
+ let existing_pos = tool_slots.iter().position(|s| s.block_index == tc.index);
+ let block_index = if let Some(pos) = existing_pos {
+ tool_slots[pos].block_index
+ } else {
+ let id = tc.id.clone().unwrap_or_default();
+ let name = tc
+ .function
+ .as_ref()
+ .and_then(|f| f.name.clone())
+ .unwrap_or_default();
+ if id.is_empty() || name.is_empty() {
+ // Defensive: skip out-of-order fragments
+ continue;
}
+ saw_tool_calls = true;
+ let bi = next_block_index;
+ next_block_index += 1;
+ tool_slots.push(ToolSlot {
+ block_index: bi,
+ id: id.clone(),
+ name: name.clone(),
+ });
+ out.push(ReducerEvent::ToolStart {
+ index: bi,
+ id,
+ name,
+ });
+ bi
+ };
+
+ if let Some(args) = tc.function.as_ref().and_then(|f| f.arguments.as_ref())
+ && !args.is_empty()
+ {
+ out.push(ReducerEvent::ToolDelta {
+ index: block_index,
+ partial_json: args.to_string(),
+ });
}
}
}
@@ -485,7 +488,7 @@ mod tests {
#[test]
fn reducer_returns_error_on_upstream_error() {
- let upstream = concat!("data: {\"error\":{\"message\":\"rate limit exceeded\"}}\n\n",);
+ let upstream = "data: {\"error\":{\"message\":\"rate limit exceeded\"}}\n\n";
let result = reduce_upstream_bytes(upstream.as_bytes());
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind, UpstreamErrorKind::Failed);
diff --git a/src/providers/kimi/translate/request.rs b/src/providers/kimi/translate/request.rs
index 6f117d2..f72362c 100644
--- a/src/providers/kimi/translate/request.rs
+++ b/src/providers/kimi/translate/request.rs
@@ -380,7 +380,7 @@ fn push_user_messages(out: &mut Vec<KimiMessage>, blocks: &[ContentBlock]) {
content: Value::String(joined),
});
} else {
- let parts: Vec<KimiUserContentPart> = buffer.drain(..).collect();
+ let parts: Vec<KimiUserContentPart> = std::mem::take(buffer);
out.push(KimiMessage::User {
role: "user".to_string(),
content: serde_json::to_value(parts).unwrap_or_default(),
@@ -481,10 +481,10 @@ fn tool_result_content(content: &Value, is_error: Option<bool>) -> Value {
}
// Collapse to string when only one text part
- if parts.len() == 1 {
- if let KimiToolResultPart::Text { text } = &parts[0] {
- return Value::String(text.clone());
- }
+ if parts.len() == 1
+ && let KimiToolResultPart::Text { text } = &parts[0]
+ {
+ return Value::String(text.clone());
}
serde_json::to_value(parts).unwrap_or(Value::String(prefix.to_string()))
diff --git a/tests/codex_websocket.rs b/tests/codex_websocket.rs
index c02143b..e85a863 100644
--- a/tests/codex_websocket.rs
+++ b/tests/codex_websocket.rs
@@ -15,6 +15,7 @@ use tokio_tungstenite::{WebSocketStream, accept_async, accept_hdr_async, connect
/// Spawn a WebSocket mock server that accepts one connection, captures
/// handshake headers, reads one text message, and calls `handler` with
/// headers and the stream. Returns the listener address as `http://addr/...`.
+#[allow(clippy::result_large_err)]
async fn websocket_mock<F, Fut>(handler: F) -> String
where
F: Fn(http::HeaderMap, WebSocketStream<TcpStream>) -> Fut + Send + 'static,
@@ -26,10 +27,7 @@ where
let ch = captured_headers.clone();
tokio::spawn(async move {
- loop {
- let Ok((stream, _)) = listener.accept().await else {
- break;
- };
+ if let Ok((stream, _)) = listener.accept().await {
let ch = ch.clone();
let ws = accept_hdr_async(stream, |req: &http::Request<()>, resp| {
let mut guard = ch.try_lock().unwrap();
@@ -40,8 +38,6 @@ where
.unwrap();
let headers = captured_headers.lock().await.clone().unwrap_or_default();
tokio::spawn(handler(headers, ws));
- // Only handle one connection per test
- break;
}
});
@@ -92,7 +88,7 @@ async fn websocket_concurrent_requests() {
"input": [{"role":"user","content":[{"type":"input_text","text":format!("msg {i}")}]}]
});
let _ = writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await;
}
}));
@@ -146,7 +142,7 @@ async fn websocket_request_serializes_response_create() {
"text": {"verbosity": "low"},
});
writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await
.unwrap();
}
@@ -183,21 +179,18 @@ async fn websocket_collects_sse_events_until_terminal() {
let req = serde_json::json!({"type": "response.create", "model": "gpt-5.5", "input": []});
writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await
.unwrap();
drop(writer);
let mut sse_body = Vec::new();
- loop {
- match tokio::time::timeout(Duration::from_millis(500), reader.next()).await {
- Ok(Some(Ok(Message::Text(text)))) => {
- sse_body.extend_from_slice(&sse_data(&text));
- if text.contains("response.completed") {
- break;
- }
- }
- _ => break,
+ while let Ok(Some(Ok(Message::Text(text)))) =
+ tokio::time::timeout(Duration::from_millis(500), reader.next()).await
+ {
+ sse_body.extend_from_slice(&sse_data(&text));
+ if text.contains("response.completed") {
+ break;
}
}
@@ -242,22 +235,17 @@ async fn websocket_idle_timeout_no_events() {
let req = serde_json::json!({"type": "response.create", "model": "gpt-5.5", "input": []});
writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await
.unwrap();
drop(writer);
let timeout = tokio::time::timeout(Duration::from_millis(100), async {
- loop {
- match reader.next().await {
- Some(Ok(Message::Text(_))) => continue,
- _ => break,
- }
- }
+ while let Some(Ok(Message::Text(_))) = reader.next().await {}
})
.await;
- assert!(timeout.is_err() || timeout.unwrap() == ());
+ assert!(timeout.is_err() || timeout.is_ok());
}
// ---------------------------------------------------------------------------
@@ -282,23 +270,20 @@ async fn websocket_invalidation_on_error() {
let req = serde_json::json!({"type": "response.create", "model": "gpt-5.5", "input": []});
writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await
.unwrap();
drop(writer);
let mut got_error = false;
- loop {
- match tokio::time::timeout(Duration::from_millis(500), reader.next()).await {
- Ok(Some(Ok(Message::Text(text)))) => {
- if text.contains("response.failed") {
- got_error = true;
- }
- if text.contains("response.failed") || text.contains("response.completed") {
- break;
- }
- }
- _ => break,
+ while let Ok(Some(Ok(Message::Text(text)))) =
+ tokio::time::timeout(Duration::from_millis(500), reader.next()).await
+ {
+ if text.contains("response.failed") {
+ got_error = true;
+ }
+ if text.contains("response.failed") || text.contains("response.completed") {
+ break;
}
}
assert!(got_error, "expected response.failed event");
@@ -314,7 +299,7 @@ async fn websocket_soak_concurrent_requests() {
let counter = Arc::new(AtomicUsize::new(0));
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
- let counter_clone = counter.clone();
+ let _counter_clone = counter.clone();
let server_handle = tokio::spawn(async move {
for _ in 0..total {
@@ -344,7 +329,7 @@ async fn websocket_soak_concurrent_requests() {
"input": [{"role":"user","content":[{"type":"input_text","text":format!("soak {i}")}]}]
});
let _ = writer
- .send(Message::Text(serde_json::to_string(&req).unwrap().into()))
+ .send(Message::Text(serde_json::to_string(&req).unwrap()))
.await;
drop(writer);
let _ = tokio::time::timeout(Duration::from_millis(500), reader.next()).await;
diff --git a/tests/foundation.rs b/tests/foundation.rs
index 5f0df71..547d3a3 100644
--- a/tests/foundation.rs
+++ b/tests/foundation.rs
@@ -115,11 +115,10 @@ fn traffic_capture_helpers() {
assert_eq!(sanitize_path_part("a*b@c/def"), "a_b_c_def");
let path = sanitize_path_part(
- &"/a\
-/path"
- .to_string(),
+ "/a\
+/path",
);
- assert_eq!(path.chars().all(|ch| ch != '/'), true);
+ assert!(path.chars().all(|ch| ch != '/'));
let sample = json!({"access_token":"abc","nested":{"chatgpt-account-id":"x","value":1}});
let redacted = redact_traffic(&sample);