1use std::fs::{self, OpenOptions};
2use std::io::Write;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Mutex, OnceLock};
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use base64::Engine;
9use serde::{Deserialize, Serialize};
10use serde_json::Value as JsonValue;
11
12use crate::config::proxy_home_dir;
13use crate::state::{RouteDecisionProvenance, SessionIdentitySource};
14use crate::usage::UsageMetrics;
15
16#[path = "logging/control_trace.rs"]
17mod control_trace_impl;
18
19use control_trace_impl::append_control_trace_payload;
20pub use control_trace_impl::{
21 ControlTraceDetail, ControlTraceLogEntry, control_trace_path, log_retry_trace,
22 read_recent_control_trace_entries,
23};
24
25#[derive(Debug, Clone, Copy)]
26pub struct HttpDebugOptions {
27 pub enabled: bool,
28 pub all: bool,
29 pub max_body_bytes: usize,
30}
31
32#[derive(Debug, Clone, Copy)]
33pub struct HttpWarnOptions {
34 pub enabled: bool,
35 pub all: bool,
36 pub max_body_bytes: usize,
37}
38
39pub fn should_log_request_body_preview() -> bool {
40 env_bool_default("CODEX_HELPER_HTTP_LOG_REQUEST_BODY", false)
43}
44
45pub fn now_ms() -> u64 {
46 SystemTime::now()
47 .duration_since(UNIX_EPOCH)
48 .map(|d| d.as_millis() as u64)
49 .unwrap_or(0)
50}
51
52pub fn request_trace_id(service: &str, request_id: u64) -> String {
53 let service = service.trim();
54 if service.is_empty() {
55 format!("request-{request_id}")
56 } else {
57 format!("{service}-{request_id}")
58 }
59}
60
61fn env_bool(key: &str) -> bool {
62 let Ok(v) = std::env::var(key) else {
63 return false;
64 };
65 matches!(
66 v.trim().to_ascii_lowercase().as_str(),
67 "1" | "true" | "yes" | "y" | "on"
68 )
69}
70
71fn env_bool_default(key: &str, default: bool) -> bool {
72 match std::env::var(key) {
73 Ok(v) => matches!(
74 v.trim().to_ascii_lowercase().as_str(),
75 "1" | "true" | "yes" | "y" | "on"
76 ),
77 Err(_) => default,
78 }
79}
80
81pub fn http_debug_options() -> HttpDebugOptions {
82 static OPT: OnceLock<HttpDebugOptions> = OnceLock::new();
83 *OPT.get_or_init(|| {
84 let enabled = env_bool("CODEX_HELPER_HTTP_DEBUG");
85 let all = env_bool("CODEX_HELPER_HTTP_DEBUG_ALL");
86 let max_body_bytes = std::env::var("CODEX_HELPER_HTTP_DEBUG_BODY_MAX")
87 .ok()
88 .and_then(|s| s.trim().parse::<usize>().ok())
89 .filter(|&n| n > 0)
90 .unwrap_or(64 * 1024);
91 HttpDebugOptions {
92 enabled,
93 all,
94 max_body_bytes,
95 }
96 })
97}
98
99pub fn http_warn_options() -> HttpWarnOptions {
100 static OPT: OnceLock<HttpWarnOptions> = OnceLock::new();
101 *OPT.get_or_init(|| {
102 let enabled = env_bool_default("CODEX_HELPER_HTTP_WARN", true);
105 let all = env_bool_default("CODEX_HELPER_HTTP_WARN_ALL", false);
106 let max_body_bytes = std::env::var("CODEX_HELPER_HTTP_WARN_BODY_MAX")
107 .ok()
108 .and_then(|s| s.trim().parse::<usize>().ok())
109 .filter(|&n| n > 0)
110 .unwrap_or(8 * 1024);
111 HttpWarnOptions {
112 enabled,
113 all,
114 max_body_bytes,
115 }
116 })
117}
118
119pub fn should_include_http_debug(status_code: u16) -> bool {
120 let opt = http_debug_options();
121 if !opt.enabled {
122 return false;
123 }
124 if opt.all {
125 return true;
126 }
127 !(200..300).contains(&status_code)
128}
129
130pub fn should_include_http_warn(status_code: u16) -> bool {
131 let opt = http_warn_options();
132 if !opt.enabled {
133 return false;
134 }
135 if opt.all {
136 return true;
137 }
138 !(200..300).contains(&status_code)
139}
140
141#[derive(Debug, Serialize, Clone)]
142pub struct HeaderEntry {
143 pub name: String,
144 pub value: String,
145}
146
147#[derive(Debug, Serialize, Clone)]
148pub struct AuthResolutionLog {
149 #[serde(skip_serializing_if = "Option::is_none")]
151 pub authorization: Option<String>,
152 #[serde(skip_serializing_if = "Option::is_none")]
154 pub x_api_key: Option<String>,
155}
156
157#[derive(Debug, Serialize, Clone)]
158pub struct BodyPreview {
159 #[serde(skip_serializing_if = "Option::is_none")]
160 pub content_type: Option<String>,
161 pub encoding: String,
162 pub data: String,
163 pub truncated: bool,
164 pub original_len: usize,
165}
166
167fn normalize_content_type(content_type: Option<&str>) -> Option<&str> {
168 let ct = content_type?.trim();
169 let (base, _) = ct.split_once(';').unwrap_or((ct, ""));
170 let base = base.trim();
171 if base.is_empty() { None } else { Some(base) }
172}
173
174fn is_textual_content_type(content_type: Option<&str>) -> bool {
175 let Some(ct) = normalize_content_type(content_type) else {
176 return false;
177 };
178 ct.starts_with("text/")
179 || ct == "application/json"
180 || ct.ends_with("+json")
181 || ct == "application/x-www-form-urlencoded"
182 || ct == "application/xml"
183 || ct.ends_with("+xml")
184 || ct == "text/event-stream"
185}
186
187pub fn make_body_preview(bytes: &[u8], content_type: Option<&str>, max: usize) -> BodyPreview {
188 let original_len = bytes.len();
189 let take = original_len.min(max);
190 let truncated = original_len > take;
191 let slice = &bytes[..take];
192
193 if is_textual_content_type(content_type) {
194 let text = String::from_utf8_lossy(slice).into_owned();
195 return BodyPreview {
196 content_type: normalize_content_type(content_type).map(|s| s.to_string()),
197 encoding: "utf8".to_string(),
198 data: text,
199 truncated,
200 original_len,
201 };
202 }
203
204 let b64 = base64::engine::general_purpose::STANDARD.encode(slice);
205 BodyPreview {
206 content_type: normalize_content_type(content_type).map(|s| s.to_string()),
207 encoding: "base64".to_string(),
208 data: b64,
209 truncated,
210 original_len,
211 }
212}
213
214#[derive(Debug, Serialize, Clone)]
215pub struct HttpDebugLog {
216 #[serde(skip_serializing_if = "Option::is_none")]
217 pub request_body_len: Option<usize>,
218 #[serde(skip_serializing_if = "Option::is_none")]
219 pub upstream_request_body_len: Option<usize>,
220 #[serde(skip_serializing_if = "Option::is_none")]
222 pub upstream_headers_ms: Option<u64>,
223 #[serde(skip_serializing_if = "Option::is_none")]
225 pub upstream_first_chunk_ms: Option<u64>,
226 #[serde(skip_serializing_if = "Option::is_none")]
228 pub upstream_body_read_ms: Option<u64>,
229 #[serde(skip_serializing_if = "Option::is_none")]
231 pub upstream_error_class: Option<String>,
232 #[serde(skip_serializing_if = "Option::is_none")]
234 pub upstream_error_hint: Option<String>,
235 #[serde(skip_serializing_if = "Option::is_none")]
237 pub upstream_cf_ray: Option<String>,
238 pub client_uri: String,
239 pub target_url: String,
240 pub client_headers: Vec<HeaderEntry>,
241 pub upstream_request_headers: Vec<HeaderEntry>,
242 #[serde(skip_serializing_if = "Option::is_none")]
243 pub auth_resolution: Option<AuthResolutionLog>,
244 #[serde(skip_serializing_if = "Option::is_none")]
245 pub client_body: Option<BodyPreview>,
246 #[serde(skip_serializing_if = "Option::is_none")]
247 pub upstream_request_body: Option<BodyPreview>,
248 #[serde(skip_serializing_if = "Option::is_none")]
249 pub upstream_response_headers: Option<Vec<HeaderEntry>>,
250 #[serde(skip_serializing_if = "Option::is_none")]
251 pub upstream_response_body: Option<BodyPreview>,
252 #[serde(skip_serializing_if = "Option::is_none")]
253 pub upstream_error: Option<String>,
254}
255
256#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
257pub struct ServiceTierLog {
258 #[serde(skip_serializing_if = "Option::is_none")]
259 pub requested: Option<String>,
260 #[serde(skip_serializing_if = "Option::is_none")]
261 pub effective: Option<String>,
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub actual: Option<String>,
264}
265
266fn service_tier_log_is_empty(value: &ServiceTierLog) -> bool {
267 value.requested.is_none() && value.effective.is_none() && value.actual.is_none()
268}
269
270#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
271pub struct CodexBridgeLog {
272 pub patch_mode: String,
273 #[serde(default, skip_serializing_if = "bool_is_false")]
274 pub remote_compaction_v1_request: bool,
275 #[serde(default, skip_serializing_if = "bool_is_false")]
276 pub responses_websocket_request: bool,
277 #[serde(default, skip_serializing_if = "bool_is_false")]
278 pub strips_client_auth: bool,
279}
280
281#[derive(Debug, Serialize)]
282pub struct RequestLog<'a> {
283 pub timestamp_ms: u64,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub request_id: Option<u64>,
286 #[serde(skip_serializing_if = "Option::is_none")]
287 pub trace_id: Option<String>,
288 pub service: &'a str,
289 pub method: &'a str,
290 pub path: &'a str,
291 pub status_code: u16,
292 pub duration_ms: u64,
293 #[serde(skip_serializing_if = "Option::is_none")]
297 pub ttfb_ms: Option<u64>,
298 #[serde(skip_serializing_if = "Option::is_none")]
299 pub station_name: Option<&'a str>,
300 #[serde(skip_serializing_if = "Option::is_none")]
301 pub provider_id: Option<String>,
302 #[serde(skip_serializing_if = "Option::is_none")]
303 pub endpoint_id: Option<String>,
304 #[serde(skip_serializing_if = "Option::is_none")]
305 pub provider_endpoint_key: Option<String>,
306 pub upstream_base_url: &'a str,
307 #[serde(skip_serializing_if = "Option::is_none")]
308 pub session_id: Option<String>,
309 #[serde(skip_serializing_if = "Option::is_none")]
310 pub session_identity_source: Option<SessionIdentitySource>,
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub cwd: Option<String>,
313 #[serde(skip_serializing_if = "Option::is_none")]
314 pub model: Option<String>,
315 #[serde(skip_serializing_if = "Option::is_none")]
316 pub reasoning_effort: Option<String>,
317 #[serde(skip_serializing_if = "service_tier_log_is_empty", default)]
318 pub service_tier: ServiceTierLog,
319 #[serde(skip_serializing_if = "Option::is_none")]
320 pub codex_bridge: Option<CodexBridgeLog>,
321 #[serde(skip_serializing_if = "Option::is_none")]
322 pub usage: Option<UsageMetrics>,
323 #[serde(skip_serializing_if = "Option::is_none")]
324 pub http_debug: Option<HttpDebugLog>,
325 #[serde(skip_serializing_if = "Option::is_none")]
326 pub http_debug_ref: Option<HttpDebugRef>,
327 #[serde(skip_serializing_if = "Option::is_none")]
328 pub route_decision: Option<RouteDecisionProvenance>,
329 #[serde(skip_serializing_if = "Option::is_none")]
330 pub retry: Option<RetryInfo>,
331}
332
333#[derive(Debug, Serialize, Clone)]
334pub struct HttpDebugRef {
335 pub id: String,
336 pub file: String,
337}
338
339fn route_attempts_is_empty(value: &[RouteAttemptLog]) -> bool {
340 value.is_empty()
341}
342
343fn route_attempt_avoid_for_station_is_empty(value: &[usize]) -> bool {
344 value.is_empty()
345}
346
347fn route_attempt_avoided_candidate_indices_is_empty(value: &[usize]) -> bool {
348 value.is_empty()
349}
350
351fn route_attempt_route_path_is_empty(value: &[String]) -> bool {
352 value.is_empty()
353}
354
355fn bool_is_false(value: &bool) -> bool {
356 !*value
357}
358
359#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
360pub struct RouteAttemptLog {
361 pub attempt_index: u32,
362 #[serde(skip_serializing_if = "Option::is_none")]
363 pub provider_id: Option<String>,
364 #[serde(skip_serializing_if = "Option::is_none")]
365 pub endpoint_id: Option<String>,
366 #[serde(skip_serializing_if = "Option::is_none")]
367 pub provider_endpoint_key: Option<String>,
368 #[serde(skip_serializing_if = "Option::is_none")]
369 pub preference_group: Option<u32>,
370 #[serde(default, skip_serializing_if = "route_attempt_route_path_is_empty")]
371 pub route_path: Vec<String>,
372 #[serde(skip_serializing_if = "Option::is_none")]
373 pub provider_attempt: Option<u32>,
374 #[serde(skip_serializing_if = "Option::is_none")]
375 pub upstream_attempt: Option<u32>,
376 #[serde(skip_serializing_if = "Option::is_none")]
377 pub provider_max_attempts: Option<u32>,
378 #[serde(skip_serializing_if = "Option::is_none")]
379 pub upstream_max_attempts: Option<u32>,
380 #[serde(skip_serializing_if = "Option::is_none")]
381 pub station_name: Option<String>,
382 #[serde(skip_serializing_if = "Option::is_none")]
383 pub upstream_base_url: Option<String>,
384 #[serde(skip_serializing_if = "Option::is_none")]
385 pub upstream_index: Option<usize>,
386 #[serde(
387 default,
388 skip_serializing_if = "route_attempt_avoid_for_station_is_empty"
389 )]
390 pub avoid_for_station: Vec<usize>,
391 #[serde(
392 default,
393 skip_serializing_if = "route_attempt_avoided_candidate_indices_is_empty"
394 )]
395 pub avoided_candidate_indices: Vec<usize>,
396 #[serde(skip_serializing_if = "Option::is_none")]
397 pub avoided_total: Option<usize>,
398 #[serde(skip_serializing_if = "Option::is_none")]
399 pub total_upstreams: Option<usize>,
400 pub decision: String,
401 #[serde(skip_serializing_if = "Option::is_none")]
402 pub reason: Option<String>,
403 #[serde(skip_serializing_if = "Option::is_none")]
404 pub status_code: Option<u16>,
405 #[serde(skip_serializing_if = "Option::is_none")]
406 pub error_class: Option<String>,
407 #[serde(skip_serializing_if = "Option::is_none")]
408 pub model: Option<String>,
409 #[serde(skip_serializing_if = "Option::is_none")]
410 pub upstream_headers_ms: Option<u64>,
411 #[serde(skip_serializing_if = "Option::is_none")]
412 pub duration_ms: Option<u64>,
413 #[serde(skip_serializing_if = "Option::is_none")]
414 pub cooldown_secs: Option<u64>,
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub cooldown_reason: Option<String>,
417 #[serde(default, skip_serializing_if = "bool_is_false")]
418 pub skipped: bool,
419 pub raw: String,
420}
421
422#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
423pub struct RetryInfo {
424 pub attempts: u32,
425 pub upstream_chain: Vec<String>,
426 #[serde(default, skip_serializing_if = "route_attempts_is_empty")]
427 pub route_attempts: Vec<RouteAttemptLog>,
428}
429
430impl RetryInfo {
431 pub fn route_attempts_or_derived(&self) -> Vec<RouteAttemptLog> {
432 if self.route_attempts.is_empty() {
433 parse_route_attempts_from_chain(&self.upstream_chain)
434 } else {
435 self.route_attempts.clone()
436 }
437 }
438
439 pub fn touches_station(&self, station_name: &str) -> bool {
440 let station_name = station_name.trim();
441 if station_name.is_empty() {
442 return false;
443 }
444 self.route_attempts_or_derived()
445 .iter()
446 .any(|attempt| attempt.station_name.as_deref() == Some(station_name))
447 }
448
449 pub fn touched_other_station(&self, final_station: Option<&str>) -> bool {
450 let Some(final_station) = final_station
451 .map(str::trim)
452 .filter(|station| !station.is_empty())
453 else {
454 return false;
455 };
456
457 self.route_attempts_or_derived()
458 .iter()
459 .filter_map(|attempt| attempt.station_name.as_deref())
460 .any(|station| station != final_station)
461 }
462}
463
464pub(crate) fn parse_route_attempts_from_chain(chain: &[String]) -> Vec<RouteAttemptLog> {
465 chain
466 .iter()
467 .enumerate()
468 .map(|(idx, raw)| parse_route_attempt_from_chain_entry(raw, idx as u32))
469 .collect()
470}
471
472fn parse_route_attempt_from_chain_entry(raw: &str, attempt_index: u32) -> RouteAttemptLog {
473 let raw = raw.trim();
474 let mut attempt = RouteAttemptLog {
475 attempt_index,
476 decision: "observed".to_string(),
477 raw: raw.to_string(),
478 ..Default::default()
479 };
480
481 if raw.starts_with("all_upstreams_avoided") {
482 attempt.decision = "all_upstreams_avoided".to_string();
483 attempt.reason = route_chain_value(raw, "total").map(|total| format!("total={total}"));
484 attempt.skipped = true;
485 return attempt;
486 }
487
488 let (target, metadata, upstream_index) = split_route_chain_entry(raw);
489 attempt.upstream_index = upstream_index;
490 if let Some(target) = target {
491 let (station_name, upstream_base_url) = parse_route_chain_target(target);
492 attempt.station_name = station_name;
493 attempt.upstream_base_url = upstream_base_url;
494 }
495 apply_route_chain_identity_metadata(&mut attempt, raw);
496
497 if let Some(status_code) =
498 route_chain_value(metadata, "status").and_then(|value| value.parse::<u16>().ok())
499 {
500 attempt.status_code = Some(status_code);
501 attempt.decision = if (200..300).contains(&status_code) {
502 "completed".to_string()
503 } else {
504 "failed_status".to_string()
505 };
506 }
507
508 if let Some(error_class) =
509 route_chain_value(metadata, "class").filter(|value| !value.eq_ignore_ascii_case("-"))
510 {
511 attempt.error_class = Some(error_class);
512 }
513 if let Some(model) = route_chain_value(metadata, "model") {
514 attempt.model = Some(model);
515 }
516
517 if let Some(model) = route_chain_value(metadata, "skipped_unsupported_model") {
518 attempt.decision = "skipped_capability_mismatch".to_string();
519 attempt.reason = Some("unsupported_model".to_string());
520 attempt.model = Some(model);
521 attempt.skipped = true;
522 }
523
524 if let Some(error) = route_chain_value(metadata, "transport_error") {
525 attempt.decision = "failed_transport".to_string();
526 attempt.reason = Some(error);
527 attempt.error_class = Some("upstream_transport_error".to_string());
528 }
529
530 if let Some(error) = route_chain_value(metadata, "target_build_error") {
531 attempt.decision = "failed_target_build".to_string();
532 attempt.reason = Some(error);
533 attempt.error_class = Some("target_build_error".to_string());
534 }
535
536 if let Some(error) = route_chain_value(metadata, "body_read_error") {
537 attempt.decision = "failed_body_read".to_string();
538 attempt.reason = Some(error);
539 attempt.error_class = Some("upstream_body_read_error".to_string());
540 }
541 if let Some(error) = route_chain_value(metadata, "body_too_large") {
542 attempt.decision = "failed_body_too_large".to_string();
543 attempt.reason = Some(error);
544 attempt.error_class = Some("upstream_response_body_too_large".to_string());
545 }
546
547 attempt
548}
549
550fn apply_route_chain_identity_metadata(attempt: &mut RouteAttemptLog, raw: &str) {
551 if let Some(station) = route_chain_value(raw, "station") {
552 attempt.station_name = non_empty_str(station.as_str()).map(ToOwned::to_owned);
553 }
554 if let Some(provider_endpoint_key) = route_chain_value(raw, "endpoint") {
555 let provider_endpoint_key = provider_endpoint_key.trim().to_string();
556 if !provider_endpoint_key.is_empty() && provider_endpoint_key != "-" {
557 let parts = provider_endpoint_key.split('/').collect::<Vec<_>>();
558 if parts.len() >= 3 {
559 attempt.provider_id = non_empty_str(parts[1]).map(ToOwned::to_owned);
560 attempt.endpoint_id = non_empty_str(parts[2]).map(ToOwned::to_owned);
561 }
562 attempt.provider_endpoint_key = Some(provider_endpoint_key);
563 }
564 }
565 if let Some(group) = route_chain_value(raw, "group").and_then(|value| value.parse::<u32>().ok())
566 {
567 attempt.preference_group = Some(group);
568 }
569 if let Some(station) = route_chain_value(raw, "compat_station") {
570 attempt.station_name = non_empty_str(station.as_str()).map(ToOwned::to_owned);
571 }
572 if let Some(index) =
573 route_chain_value(raw, "upstream_index").and_then(|value| value.parse::<usize>().ok())
574 {
575 attempt.upstream_index = Some(index);
576 }
577 if let Some(url) = route_chain_value(raw, "url") {
578 attempt.upstream_base_url = non_empty_str(url.as_str()).map(ToOwned::to_owned);
579 }
580 if let Some(indices) = route_chain_value(raw, "avoid_candidates") {
581 attempt.avoided_candidate_indices = parse_usize_list(indices.as_str());
582 }
583 if let Some(indices) = route_chain_value(raw, "avoid") {
584 attempt.avoid_for_station = parse_usize_list(indices.as_str());
585 }
586}
587
588fn parse_usize_list(raw: &str) -> Vec<usize> {
589 raw.split(',')
590 .filter_map(|part| part.trim().parse::<usize>().ok())
591 .collect()
592}
593
594fn split_route_chain_entry(raw: &str) -> (Option<&str>, &str, Option<usize>) {
595 if let Some(idx_start) = raw.find(" (idx=") {
596 let target = raw[..idx_start].trim();
597 let after_idx = &raw[idx_start + " (idx=".len()..];
598 if let Some(idx_end) = after_idx.find(')') {
599 let upstream_index = after_idx[..idx_end].trim().parse::<usize>().ok();
600 let metadata = after_idx[idx_end + 1..].trim();
601 return (non_empty_str(target), metadata, upstream_index);
602 }
603 return (non_empty_str(target), after_idx.trim(), None);
604 }
605
606 if let Some(metadata_start) = first_route_chain_key_start(raw) {
607 let target = raw[..metadata_start].trim();
608 let metadata = raw[metadata_start..].trim();
609 return (non_empty_str(target), metadata, None);
610 }
611
612 (non_empty_str(raw), "", None)
613}
614
615fn parse_route_chain_target(target: &str) -> (Option<String>, Option<String>) {
616 let target = target.trim();
617 if target.is_empty() {
618 return (None, None);
619 }
620 if target.starts_with("http://") || target.starts_with("https://") {
621 return (None, Some(target.to_string()));
622 }
623
624 if let Some(pos) = target.find(":http://").or_else(|| target.find(":https://")) {
625 let station = target[..pos].trim();
626 let base_url = target[pos + 1..].trim();
627 return (
628 non_empty_str(station).map(ToOwned::to_owned),
629 non_empty_str(base_url).map(ToOwned::to_owned),
630 );
631 }
632
633 (None, Some(target.to_string()))
634}
635
636fn first_route_chain_key_start(raw: &str) -> Option<usize> {
637 ROUTE_CHAIN_KEYS
638 .iter()
639 .filter_map(|key| find_route_chain_key(raw, format!("{key}=").as_str()))
640 .min()
641}
642
643fn route_chain_value(raw: &str, key: &str) -> Option<String> {
644 let needle = format!("{key}=");
645 let start = find_route_chain_key(raw, needle.as_str())?;
646 let value_start = start + needle.len();
647 let value_end = ROUTE_CHAIN_KEYS
648 .iter()
649 .filter(|candidate| **candidate != key)
650 .filter_map(|candidate| {
651 raw[value_start..]
652 .find(&format!(" {candidate}="))
653 .map(|offset| value_start + offset)
654 })
655 .min()
656 .unwrap_or(raw.len());
657 non_empty_str(raw[value_start..value_end].trim()).map(ToOwned::to_owned)
658}
659
660fn find_route_chain_key(raw: &str, needle: &str) -> Option<usize> {
661 let mut offset = 0usize;
662 while let Some(pos) = raw[offset..].find(needle) {
663 let absolute = offset + pos;
664 if absolute == 0 || raw[..absolute].ends_with(' ') {
665 return Some(absolute);
666 }
667 offset = absolute + needle.len();
668 }
669 None
670}
671
672fn non_empty_str(value: &str) -> Option<&str> {
673 let value = value.trim();
674 if value.is_empty() { None } else { Some(value) }
675}
676
677const ROUTE_CHAIN_KEYS: &[&str] = &[
678 "status",
679 "class",
680 "model",
681 "transport_error",
682 "target_build_error",
683 "body_read_error",
684 "body_too_large",
685 "skipped_unsupported_model",
686 "total",
687 "station",
688 "endpoint",
689 "group",
690 "compat_station",
691 "upstream_index",
692 "url",
693 "avoid_candidates",
694 "avoid",
695];
696
697#[derive(Debug, Serialize)]
698struct HttpDebugLogEntry<'a> {
699 pub id: &'a str,
700 pub timestamp_ms: u64,
701 #[serde(skip_serializing_if = "Option::is_none")]
702 pub request_id: Option<u64>,
703 #[serde(skip_serializing_if = "Option::is_none")]
704 pub trace_id: Option<String>,
705 pub service: &'a str,
706 pub method: &'a str,
707 pub path: &'a str,
708 pub status_code: u16,
709 pub duration_ms: u64,
710 #[serde(skip_serializing_if = "Option::is_none")]
711 pub ttfb_ms: Option<u64>,
712 #[serde(skip_serializing_if = "Option::is_none")]
713 pub station_name: Option<&'a str>,
714 #[serde(skip_serializing_if = "Option::is_none")]
715 pub provider_id: Option<String>,
716 #[serde(skip_serializing_if = "Option::is_none")]
717 pub endpoint_id: Option<String>,
718 #[serde(skip_serializing_if = "Option::is_none")]
719 pub provider_endpoint_key: Option<String>,
720 pub upstream_base_url: &'a str,
721 #[serde(skip_serializing_if = "Option::is_none")]
722 pub session_id: Option<String>,
723 #[serde(skip_serializing_if = "Option::is_none")]
724 pub session_identity_source: Option<SessionIdentitySource>,
725 #[serde(skip_serializing_if = "Option::is_none")]
726 pub cwd: Option<String>,
727 #[serde(skip_serializing_if = "Option::is_none")]
728 pub model: Option<String>,
729 #[serde(skip_serializing_if = "Option::is_none")]
730 pub reasoning_effort: Option<String>,
731 #[serde(skip_serializing_if = "service_tier_log_is_empty", default)]
732 pub service_tier: ServiceTierLog,
733 #[serde(skip_serializing_if = "Option::is_none")]
734 pub codex_bridge: Option<CodexBridgeLog>,
735 #[serde(skip_serializing_if = "Option::is_none")]
736 pub usage: Option<UsageMetrics>,
737 #[serde(skip_serializing_if = "Option::is_none")]
738 pub route_decision: Option<RouteDecisionProvenance>,
739 #[serde(skip_serializing_if = "Option::is_none")]
740 pub retry: Option<RetryInfo>,
741 pub http_debug: HttpDebugLog,
742}
743
744#[derive(Debug, Clone, Copy)]
745struct RequestLogOptions {
746 max_bytes: u64,
747 max_files: usize,
748 only_errors: bool,
749}
750
751pub fn request_log_path() -> PathBuf {
752 proxy_home_dir().join("logs").join("requests.jsonl")
753}
754
755fn debug_log_path() -> PathBuf {
756 proxy_home_dir().join("logs").join("requests_debug.jsonl")
757}
758
759fn log_lock() -> &'static Mutex<()> {
760 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
761 LOCK.get_or_init(|| Mutex::new(()))
762}
763
764fn http_debug_split_enabled() -> bool {
765 env_bool_default("CODEX_HELPER_HTTP_DEBUG_SPLIT", true) || http_debug_options().all
768}
769
770fn request_log_options() -> RequestLogOptions {
771 static OPT: OnceLock<RequestLogOptions> = OnceLock::new();
772 *OPT.get_or_init(|| {
773 let max_bytes = std::env::var("CODEX_HELPER_REQUEST_LOG_MAX_BYTES")
774 .ok()
775 .and_then(|s| s.trim().parse::<u64>().ok())
776 .filter(|&n| n > 0)
777 .unwrap_or(50 * 1024 * 1024);
778 let max_files = std::env::var("CODEX_HELPER_REQUEST_LOG_MAX_FILES")
779 .ok()
780 .and_then(|s| s.trim().parse::<usize>().ok())
781 .filter(|&n| n > 0)
782 .unwrap_or(10);
783 let only_errors = env_bool("CODEX_HELPER_REQUEST_LOG_ONLY_ERRORS");
784 RequestLogOptions {
785 max_bytes,
786 max_files,
787 only_errors,
788 }
789 })
790}
791
792fn ensure_log_parent(path: &Path) {
793 if let Some(parent) = path.parent() {
794 let _ = fs::create_dir_all(parent);
795 }
796}
797
798fn append_json_line(path: &PathBuf, opt: RequestLogOptions, line: &str) -> bool {
799 rotate_and_prune_if_needed(path, opt);
800 if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
801 return writeln!(file, "{}", line).is_ok();
802 }
803 false
804}
805
806fn rotate_and_prune_if_needed(path: &PathBuf, opt: RequestLogOptions) {
807 if opt.max_bytes == 0 {
808 return;
809 }
810 let Ok(meta) = fs::metadata(path) else {
811 return;
812 };
813 if meta.len() < opt.max_bytes {
814 return;
815 }
816
817 let ts = SystemTime::now()
818 .duration_since(UNIX_EPOCH)
819 .map(|d| d.as_millis() as u64)
820 .unwrap_or(0);
821 let prefix = path
822 .file_stem()
823 .and_then(|s| s.to_str())
824 .unwrap_or("requests");
825 let rotated_name = format!("{prefix}.{ts}.jsonl");
826 let rotated_path = path.with_file_name(rotated_name);
827 let _ = fs::rename(path, &rotated_path);
828
829 let Some(dir) = path.parent() else {
830 return;
831 };
832 let Ok(rd) = fs::read_dir(dir) else {
833 return;
834 };
835 let mut rotated: Vec<PathBuf> = rd
836 .filter_map(|e| e.ok())
837 .map(|e| e.path())
838 .filter(|p| {
839 p.file_name()
840 .and_then(|n| n.to_str())
841 .map(|s| s.starts_with(&format!("{prefix}.")) && s.ends_with(".jsonl"))
842 .unwrap_or(false)
843 })
844 .collect();
845 if rotated.len() <= opt.max_files {
846 return;
847 }
848 rotated.sort();
849 let remove_count = rotated.len().saturating_sub(opt.max_files);
850 for p in rotated.into_iter().take(remove_count) {
851 let _ = fs::remove_file(p);
852 }
853}
854
855#[allow(clippy::too_many_arguments)]
856pub fn log_request_with_debug(
857 request_id: Option<u64>,
858 service: &str,
859 method: &str,
860 path: &str,
861 status_code: u16,
862 duration_ms: u64,
863 ttfb_ms: Option<u64>,
864 station_name: Option<&str>,
865 provider_id: Option<String>,
866 endpoint_id: Option<String>,
867 provider_endpoint_key: Option<String>,
868 upstream_base_url: &str,
869 session_id: Option<String>,
870 session_identity_source: Option<SessionIdentitySource>,
871 cwd: Option<String>,
872 model: Option<String>,
873 reasoning_effort: Option<String>,
874 service_tier: ServiceTierLog,
875 codex_bridge: Option<CodexBridgeLog>,
876 usage: Option<UsageMetrics>,
877 route_decision: Option<RouteDecisionProvenance>,
878 retry: Option<RetryInfo>,
879 http_debug: Option<HttpDebugLog>,
880) {
881 let opt = request_log_options();
882 if opt.only_errors && (200..300).contains(&status_code) {
883 return;
884 }
885
886 let ts = now_ms();
887 let trace_id = request_id.map(|id| request_trace_id(service, id));
888
889 static DEBUG_SEQ: AtomicU64 = AtomicU64::new(0);
890 let mut http_debug_for_main = http_debug;
891 let mut http_debug_ref: Option<HttpDebugRef> = None;
892
893 let log_file_path = request_log_path();
894 ensure_log_parent(&log_file_path);
895
896 let _guard = match log_lock().lock() {
897 Ok(g) => g,
898 Err(e) => e.into_inner(),
899 };
900
901 if http_debug_split_enabled()
903 && let Some(h) = http_debug_for_main.take()
904 {
905 let seq = DEBUG_SEQ.fetch_add(1, Ordering::Relaxed);
906 let id = format!("{ts}-{seq}");
907 let debug_entry = HttpDebugLogEntry {
908 id: &id,
909 timestamp_ms: ts,
910 request_id,
911 trace_id: trace_id.clone(),
912 service,
913 method,
914 path,
915 status_code,
916 duration_ms,
917 ttfb_ms,
918 station_name,
919 provider_id: provider_id.clone(),
920 endpoint_id: endpoint_id.clone(),
921 provider_endpoint_key: provider_endpoint_key.clone(),
922 upstream_base_url,
923 session_id: session_id.clone(),
924 session_identity_source,
925 cwd: cwd.clone(),
926 model: model.clone(),
927 reasoning_effort: reasoning_effort.clone(),
928 service_tier: service_tier.clone(),
929 codex_bridge: codex_bridge.clone(),
930 usage: usage.clone(),
931 route_decision: route_decision.clone(),
932 retry: retry.clone(),
933 http_debug: h,
934 };
935
936 let debug_path = debug_log_path();
937 ensure_log_parent(&debug_path);
938 let mut wrote_debug = false;
939 if let Ok(line) = serde_json::to_string(&debug_entry) {
940 wrote_debug = append_json_line(&debug_path, opt, &line);
941 }
942
943 if wrote_debug {
944 http_debug_ref = Some(HttpDebugRef {
945 id,
946 file: "requests_debug.jsonl".to_string(),
947 });
948 } else {
949 let HttpDebugLogEntry { http_debug, .. } = debug_entry;
951 http_debug_for_main = Some(http_debug);
952 }
953 }
954
955 let entry = RequestLog {
956 timestamp_ms: ts,
957 request_id,
958 trace_id,
959 service,
960 method,
961 path,
962 status_code,
963 duration_ms,
964 ttfb_ms,
965 station_name,
966 provider_id,
967 endpoint_id,
968 provider_endpoint_key,
969 upstream_base_url,
970 session_id,
971 session_identity_source,
972 cwd,
973 model,
974 reasoning_effort,
975 service_tier,
976 codex_bridge,
977 usage,
978 http_debug: http_debug_for_main,
979 http_debug_ref,
980 route_decision,
981 retry,
982 };
983
984 if let Ok(line) = serde_json::to_string(&entry) {
985 let _ = append_json_line(&log_file_path, opt, &line);
986 }
987
988 if let Ok(payload) = serde_json::to_value(&entry) {
989 append_control_trace_payload(
990 opt,
991 "request_completed",
992 Some(service),
993 request_id,
994 Some("request_completed"),
995 ts,
996 payload,
997 );
998 }
999}
1000
1001#[cfg(test)]
1002#[path = "logging/tests.rs"]
1003mod tests;