diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index dd1139d04a..37534b0b3a 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5907,7 +5907,6 @@ dependencies = [ "anyhow", "base64 0.22.1", "chrono", - "codex-http-client", "codex-otel", "codex-protocol", "codex-utils-absolute-path", diff --git a/codex-rs/code-mode-host/Cargo.toml b/codex-rs/code-mode-host/Cargo.toml index 80865b95ac..60eb2121cd 100644 --- a/codex-rs/code-mode-host/Cargo.toml +++ b/codex-rs/code-mode-host/Cargo.toml @@ -17,7 +17,6 @@ path = "src/lib.rs" workspace = true [dependencies] -codex-http-client = { workspace = true } anyhow = { workspace = true } axum = { workspace = true, features = ["http1", "tokio", "ws"] } clap = { workspace = true, features = ["derive"] } @@ -39,6 +38,7 @@ uuid = { workspace = true, features = ["v4"] } [dev-dependencies] codex-core = { workspace = true } +codex-http-client = { workspace = true } tokio = { workspace = true, features = ["test-util"] } codex-plugin-host = { workspace = true } codex-code-mode = { workspace = true } diff --git a/codex-rs/code-mode-host/src/main.rs b/codex-rs/code-mode-host/src/main.rs index 3757f9b082..b28b0c7b7c 100644 --- a/codex-rs/code-mode-host/src/main.rs +++ b/codex-rs/code-mode-host/src/main.rs @@ -1,14 +1,8 @@ -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::PathBuf; use std::time::Duration; -use anyhow::Context; use clap::Parser; -use codex_otel::OtelExporter; -use codex_otel::OtelHttpProtocol; +use codex_otel::BlockingHttpService; use codex_otel::OtelProvider; -use codex_otel::OtelSettings; use codex_otel_trace_websocket::TraceWebSocket; use tracing_subscriber::Layer; use tracing_subscriber::layer::SubscriberExt; @@ -103,27 +97,11 @@ fn main() -> anyhow::Result<()> { } fn build_trace_provider(endpoint: &str) -> anyhow::Result { - OtelProvider::try_new_http_traces(&OtelSettings { - headers_helper: None, - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: "code-mode-host".to_string(), - service_name: "codex-code-mode-host".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("/tmp"), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: endpoint.to_string(), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .map_err(|error| anyhow::anyhow!("failed to build code-mode host OTEL provider: {error}"))? - .context("code-mode host OTEL trace provider was unexpectedly disabled") + BlockingHttpService { + environment: "code-mode-host", + name: "codex-code-mode-host", + version: env!("CARGO_PKG_VERSION"), + } + .traces(endpoint) + .map_err(|error| anyhow::anyhow!("failed to build code-mode host OTEL provider: {error}")) } diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index 5d5496e485..7612be4f34 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -100,6 +100,7 @@ pub fn build_provider( .as_ref() .map(|command| OtelHeadersHelper { command: command.clone(), + codex_home: config.codex_home.to_path_buf(), managed: managed_otel.is_some_and(|otel| otel.headers_helper.is_some()), apply_to_logs: helper_targets.is_none_or(|targets| targets.logs), apply_to_traces: helper_targets.is_none_or(|targets| targets.traces), @@ -116,7 +117,6 @@ pub fn build_provider( http_client_factory: config.http_client_factory(), service_name: service_name.to_string(), service_version: service_version.to_string(), - codex_home: config.codex_home.to_path_buf(), environment: config.otel.environment.to_string(), exporter, trace_exporter, diff --git a/codex-rs/core/tests/suite/skills_extension.rs b/codex-rs/core/tests/suite/skills_extension.rs index bb68c4be1d..8015c0fcc0 100644 --- a/codex-rs/core/tests/suite/skills_extension.rs +++ b/codex-rs/core/tests/suite/skills_extension.rs @@ -2739,7 +2739,6 @@ async fn assert_catalog_model_switch(max_context_tokens: Option) -> Resul environment: "test".to_string(), service_name: "skills-model-switch".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: codex_home.path().to_path_buf(), exporter: OtelExporter::None, trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::OtlpHttp { diff --git a/codex-rs/exec-server/src/server/process_otel_tests.rs b/codex-rs/exec-server/src/server/process_otel_tests.rs index b1e398985b..a85872bf71 100644 --- a/codex-rs/exec-server/src/server/process_otel_tests.rs +++ b/codex-rs/exec-server/src/server/process_otel_tests.rs @@ -631,7 +631,6 @@ fn exported_logs( environment: "test".to_string(), service_name: "codex-exec-server".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: std::env::current_dir().expect("cwd"), exporter, trace_exporter: if export_traces { OtelExporter::OtlpHttp { diff --git a/codex-rs/otel/README.md b/codex-rs/otel/README.md index 277e172f2d..db728f43e6 100644 --- a/codex-rs/otel/README.md +++ b/codex-rs/otel/README.md @@ -28,7 +28,6 @@ let settings = OtelSettings { environment: "dev".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: std::path::PathBuf::from("/tmp"), exporter: OtelExporter::OtlpHttp { endpoint: "https://otlp.example.com".to_string(), headers: std::collections::HashMap::new(), diff --git a/codex-rs/otel/src/config.rs b/codex-rs/otel/src/config.rs index da7f2918d3..a6eb923c47 100644 --- a/codex-rs/otel/src/config.rs +++ b/codex-rs/otel/src/config.rs @@ -57,7 +57,6 @@ pub struct OtelSettings { pub environment: String, pub service_name: String, pub service_version: String, - pub codex_home: PathBuf, pub exporter: OtelExporter, pub trace_exporter: OtelExporter, pub metrics_exporter: OtelExporter, @@ -72,6 +71,7 @@ pub struct OtelSettings { #[derive(Clone)] pub struct OtelHeadersHelper { pub command: String, + pub codex_home: PathBuf, /// A managed executable runs directly from its parent directory. User commands run from Codex home. pub managed: bool, pub refresh_interval: Duration, diff --git a/codex-rs/otel/src/headers_helper.rs b/codex-rs/otel/src/headers_helper.rs index a68cd5edd9..0d56ec6e30 100644 --- a/codex-rs/otel/src/headers_helper.rs +++ b/codex-rs/otel/src/headers_helper.rs @@ -31,7 +31,6 @@ impl fmt::Debug for HeadersHelper { impl HeadersHelper { pub(crate) fn start( config: &OtelHeadersHelper, - cwd: &Path, policy: NetworkPolicy, ) -> io::Result> { if config.command.trim().is_empty() || config.refresh_interval.is_zero() { @@ -49,14 +48,13 @@ impl HeadersHelper { let (tx, rx) = watch::channel(None); let (stop, stopped) = oneshot::channel(); let config = config.clone(); - let cwd = cwd.to_path_buf(); std::thread::Builder::new() .name("otel-headers-helper".to_string()) .spawn(move || { runtime.block_on(async move { tokio::select! { _ = stopped => {} - _ = refresh_headers(&config, &cwd, &policy, tx) => {} + _ = refresh_headers(&config, &policy, tx) => {} } }); })?; @@ -96,7 +94,6 @@ impl Drop for HeadersHelper { async fn refresh_headers( config: &OtelHeadersHelper, - cwd: &Path, policy: &NetworkPolicy, updates: watch::Sender>, ) { @@ -106,7 +103,7 @@ async fn refresh_headers( // permit as an SDK that cannot enforce individual destinations. let result = match policy.acquire_for_unsupported_sdk() { Ok(permit) => permit - .run(run_configured_helper(config, cwd)) + .run(run_configured_helper(config)) .await .unwrap_or_else(|error| Err(error.to_string())), Err(error) => Err(error.to_string()), @@ -132,9 +129,9 @@ async fn refresh_headers( } } -async fn run_configured_helper(config: &OtelHeadersHelper, cwd: &Path) -> HeaderResult { +async fn run_configured_helper(config: &OtelHeadersHelper) -> HeaderResult { if !config.managed { - return run_helper(&config.command, cwd).await; + return run_helper(&config.command, &config.codex_home).await; } let executable = Path::new(&config.command); let parent = executable diff --git a/codex-rs/otel/src/headers_helper_tests.rs b/codex-rs/otel/src/headers_helper_tests.rs index bb4ff19753..551a26c88a 100644 --- a/codex-rs/otel/src/headers_helper_tests.rs +++ b/codex-rs/otel/src/headers_helper_tests.rs @@ -31,6 +31,7 @@ async fn restricted_policy_skips_command_until_a_refresh_is_permitted() { ); let helper = HeadersHelper::start( &OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), managed: false, command: format!("echo invocation >> calls && {}", read_command()), refresh_interval: Duration::from_millis(20), @@ -38,7 +39,6 @@ async fn restricted_policy_skips_command_until_a_refresh_is_permitted() { apply_to_traces: true, apply_to_metrics: true, }, - dir.path(), policy, ) .unwrap(); @@ -67,6 +67,7 @@ async fn concurrent_exports_share_one_helper_execution() { .unwrap(); let helper = HeadersHelper::start( &OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), managed: false, command: format!("echo invocation >> calls && {}", read_command()), refresh_interval: Duration::from_secs(3600), @@ -74,7 +75,6 @@ async fn concurrent_exports_share_one_helper_execution() { apply_to_traces: true, apply_to_metrics: true, }, - dir.path(), NetworkPolicy::unmanaged(), ) .unwrap(); @@ -103,6 +103,7 @@ async fn periodic_refresh_replaces_credentials_and_recovers_after_failure() { std::fs::write(&path, r#"{"Authorization":"first","X-Old":"old"}"#).unwrap(); let helper = HeadersHelper::start( &OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), managed: false, command: read_command().to_string(), refresh_interval: Duration::from_millis(20), @@ -110,7 +111,6 @@ async fn periodic_refresh_replaces_credentials_and_recovers_after_failure() { apply_to_traces: true, apply_to_metrics: true, }, - dir.path(), NetworkPolicy::unmanaged(), ) .unwrap(); @@ -146,6 +146,7 @@ async fn missing_managed_executable_reports_path_and_os_error() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("missing-helper.exe"); let helper = OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), command: path.to_str().unwrap().to_owned(), managed: true, refresh_interval: Duration::from_secs(60), @@ -153,9 +154,7 @@ async fn missing_managed_executable_reports_path_and_os_error() { apply_to_traces: true, apply_to_metrics: true, }; - let error = run_configured_helper(&helper, dir.path()) - .await - .unwrap_err(); + let error = run_configured_helper(&helper).await.unwrap_err(); assert!(error.contains(path.to_str().unwrap()), "{error}"); let os_error = std::fs::metadata(&path).unwrap_err(); assert_eq!(os_error.kind(), std::io::ErrorKind::NotFound); @@ -181,6 +180,7 @@ async fn failed_helper_prevents_http_export_even_with_static_credentials() { listener.set_nonblocking(true).unwrap(); let helper = HeadersHelper::start( &OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), managed: false, command: "exit 1".to_string(), refresh_interval: Duration::from_secs(3600), @@ -188,7 +188,6 @@ async fn failed_helper_prevents_http_export_even_with_static_credentials() { apply_to_traces: true, apply_to_metrics: true, }, - dir.path(), NetworkPolicy::unmanaged(), ) .unwrap(); @@ -218,6 +217,7 @@ async fn failed_helper_prevents_http_export_even_with_static_credentials() { async fn grpc_and_builtin_metrics_do_not_start_the_helper() { use crate::config::OtelExporter; let helper = OtelHeadersHelper { + codex_home: ".".into(), managed: false, command: String::new(), refresh_interval: Duration::ZERO, @@ -242,7 +242,6 @@ async fn grpc_and_builtin_metrics_do_not_start_the_helper() { environment: "test".to_string(), service_name: "test".to_string(), service_version: "test".to_string(), - codex_home: std::path::PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::None, metrics_exporter: exporter, diff --git a/codex-rs/otel/src/lib.rs b/codex-rs/otel/src/lib.rs index 35dcac0d2e..9e710631c3 100644 --- a/codex-rs/otel/src/lib.rs +++ b/codex-rs/otel/src/lib.rs @@ -37,6 +37,8 @@ pub use crate::metrics::runtime_metrics::RuntimeMetricTotals; pub use crate::metrics::runtime_metrics::RuntimeMetricsSummary; pub use crate::metrics::timer::Timer; pub use crate::metrics::*; +pub use crate::provider::BlockingHttpService; +pub use crate::provider::BlockingMetricsDestination; pub use crate::provider::OtelProvider; pub use crate::skill_invocation::SkillInvocationEvent; pub use crate::skill_invocation::SkillInvocationType; diff --git a/codex-rs/otel/src/metrics/client.rs b/codex-rs/otel/src/metrics/client.rs index 369b5824ed..86127ce49f 100644 --- a/codex-rs/otel/src/metrics/client.rs +++ b/codex-rs/otel/src/metrics/client.rs @@ -12,6 +12,8 @@ use crate::metrics::validation::validate_metric_name; use crate::metrics::validation::validate_tag_key; use crate::metrics::validation::validate_tag_value; use crate::metrics::validation::validate_tags; +use crate::provider::AllExporters; +use crate::provider::ExporterScope; use codex_utils_string::sanitize_metric_tag_value; use opentelemetry::KeyValue; use opentelemetry::metrics::Counter; @@ -350,12 +352,10 @@ pub struct MetricsClient { impl MetricsClient { /// Build a metrics client from configuration and validate defaults. pub fn new(config: MetricsConfig) -> Result { - Self::new_with_transport::(config) + Self::new_with_exporters::(config) } - pub(crate) fn new_with_transport( - config: MetricsConfig, - ) -> Result { + pub(crate) fn new_with_exporters(config: MetricsConfig) -> Result { let MetricsConfig { headers_helper, http_client_factory, @@ -406,7 +406,7 @@ impl MetricsClient { .as_deref(), ); let exporter = crate::network_policy::PolicyExporter { - exporter: build_otlp_metric_exporter::( + exporter: build_otlp_metric_exporter::( exporter, temporality, &http_client_factory, @@ -668,7 +668,7 @@ fn otlp_metrics_temporality(exporter: &OtelExporter, preference: Option<&str>) - } } -fn build_otlp_metric_exporter( +fn build_otlp_metric_exporter( exporter: OtelExporter, temporality: Temporality, factory: &codex_http_client::HttpClientFactory, @@ -688,7 +688,7 @@ fn build_otlp_metric_exporter( .into_iter() .all(|key| std::env::var_os(key).is_none()) .then_some(Compression::Zstd); - build_otlp_metric_exporter::( + build_otlp_metric_exporter::( crate::config::resolve_exporter(&OtelExporter::Statsig), temporality, factory, @@ -696,7 +696,7 @@ fn build_otlp_metric_exporter( compression, ) } - OtelExporter::OtlpGrpc { .. } if !ALLOW_GRPC => Err(MetricsError::InvalidConfig { + OtelExporter::OtlpGrpc { .. } if !E::ALL => Err(MetricsError::InvalidConfig { message: "this provider requires OTLP/HTTP for metrics".into(), }), OtelExporter::OtlpGrpc { @@ -753,24 +753,26 @@ fn build_otlp_metric_exporter( exporter_builder = exporter_builder.with_compression(compression); } - if headers_helper.is_some() || factory.network_policy().is_managed() { - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, - headers_helper, - ) - .map_err(|err| MetricsError::InvalidConfig { - message: err.to_string(), - })?; - exporter_builder = exporter_builder.with_http_client(client); - } else if let Some(tls) = tls.as_ref() { - let client = - crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT) - .map_err(|err| MetricsError::InvalidConfig { - message: err.to_string(), - })?; - exporter_builder = exporter_builder.with_http_client(client); + if E::CONFIGURE_HTTP_CLIENT { + if headers_helper.is_some() || factory.network_policy().is_managed() { + let client = crate::otlp::build_async_http_client( + factory, + tls.as_ref(), + OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, + headers_helper, + ) + .map_err(|err| MetricsError::InvalidConfig { + message: err.to_string(), + })?; + exporter_builder = exporter_builder.with_http_client(client); + } else if let Some(tls) = tls.as_ref() { + let client = + crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT) + .map_err(|err| MetricsError::InvalidConfig { + message: err.to_string(), + })?; + exporter_builder = exporter_builder.with_http_client(client); + } } exporter_builder diff --git a/codex-rs/otel/src/provider.rs b/codex-rs/otel/src/provider.rs index a57ed2672b..015e91e8ae 100644 --- a/codex-rs/otel/src/provider.rs +++ b/codex-rs/otel/src/provider.rs @@ -1,3 +1,5 @@ +mod exporters; + use crate::config::OtelExporter; use crate::config::OtelHttpProtocol; use crate::config::OtelSettings; @@ -7,6 +9,12 @@ use crate::metrics::MetricsClient; use crate::metrics::MetricsConfig; use crate::targets::is_log_export_target; use crate::targets::is_trace_safe_target; +pub(crate) use exporters::AllExporters; +pub use exporters::BlockingHttpService; +pub use exporters::BlockingMetricsDestination; +pub(crate) use exporters::ExporterScope; +use exporters::HttpMetrics; +use exporters::HttpTraces; use gethostname::gethostname; use opentelemetry::Context; use opentelemetry::KeyValue; @@ -200,43 +208,36 @@ impl OtelProvider { } pub fn try_new(settings: &OtelSettings) -> Result, Box> { - Self::try_new_with_exporters::(settings) + Self::try_new_with_exporters::(settings) } /// Builds a provider for traces over OTLP/HTTP. /// Returns an error if any other signal or transport is configured. pub fn try_new_http_traces(settings: &OtelSettings) -> Result, Box> { - Self::try_new_with_exporters::(settings) + Self::try_new_with_exporters::(settings) } /// Builds a provider for metrics over OTLP/HTTP, including Statsig. /// Returns an error if any other signal or transport is configured. pub fn try_new_http_metrics(settings: &OtelSettings) -> Result, Box> { - Self::try_new_with_exporters::(settings) + Self::try_new_with_exporters::(settings) } - /// Selects the reachable exporter builders at compile time while sharing setup and shutdown. - fn try_new_with_exporters< - const ALL_EXPORTERS: bool, - const HTTP_TRACES: bool, - const HTTP_METRICS: bool, - >( + fn try_new_with_exporters( settings: &OtelSettings, ) -> Result, Box> { - let supports_traces = ALL_EXPORTERS || HTTP_TRACES; - let supports_metrics = ALL_EXPORTERS || HTTP_METRICS; let log_configured = !matches!(settings.exporter, OtelExporter::None); let trace_configured = !matches!(settings.trace_exporter, OtelExporter::None); - if (!ALL_EXPORTERS && log_configured) - || (!supports_traces && trace_configured) - || (!supports_metrics && !matches!(settings.metrics_exporter, OtelExporter::None)) + if (!E::ALL && log_configured) + || (!E::TRACES && trace_configured) + || (!E::METRICS && !matches!(settings.metrics_exporter, OtelExporter::None)) { return Err("configured exporter is not supported by this provider".into()); } - let log_enabled = ALL_EXPORTERS && log_configured; - let trace_enabled = supports_traces && trace_configured; - let metrics_enabled = supports_metrics + let log_enabled = E::ALL && log_configured; + let trace_enabled = E::TRACES && trace_configured; + let metrics_enabled = E::METRICS && !matches!( crate::config::resolve_exporter(&settings.metrics_exporter), OtelExporter::None @@ -261,9 +262,11 @@ impl OtelProvider { } crate::trace_context::validate_tracestate_entries(&settings.tracestate)?; - let (helper_for_logs, helper_for_traces, helper_for_metrics) = settings + let helper_config = settings .headers_helper .as_ref() + .filter(|_| E::CONFIGURE_HTTP_CLIENT); + let (helper_for_logs, helper_for_traces, helper_for_metrics) = helper_config .map(|helper| { ( helper.apply_to_logs @@ -275,14 +278,11 @@ impl OtelProvider { ) }) .unwrap_or_default(); - let headers_helper = settings - .headers_helper - .as_ref() + let headers_helper = helper_config .filter(|_| helper_for_logs || helper_for_traces || helper_for_metrics) .map(|config| { HeadersHelper::start( config, - &settings.codex_home, settings.http_client_factory.network_policy().clone(), ) }) @@ -302,7 +302,7 @@ impl OtelProvider { if settings.runtime_metrics { config = config.with_runtime_reader(); } - Some(MetricsClient::new_with_transport::(config)?) + Some(MetricsClient::new_with_exporters::(config)?) } else { None }; @@ -322,7 +322,7 @@ impl OtelProvider { let tracer_provider = trace_enabled .then(|| { - build_tracer_provider::( + build_tracer_provider::( &trace_resource, &settings.trace_exporter, settings.span_attributes.clone(), @@ -614,7 +614,7 @@ fn build_logger( Ok(builder.build()) } -fn build_tracer_provider( +fn build_tracer_provider( resource: &Resource, exporter: &OtelExporter, span_attributes: HashMap, @@ -626,7 +626,7 @@ fn build_tracer_provider( let span_exporter = match crate::config::resolve_exporter(exporter) { OtelExporter::None => return Ok(tracer_provider_builder(resource, span_attributes).build()), OtelExporter::Statsig => unreachable!("statsig exporter should be resolved"), - OtelExporter::OtlpGrpc { .. } if !ALLOW_GRPC => { + OtelExporter::OtlpGrpc { .. } if !E::ALL => { return Err("this provider requires OTLP/HTTP for traces".into()); } OtelExporter::OtlpGrpc { @@ -662,40 +662,6 @@ fn build_tracer_provider( } => { debug!("Using OTLP Http exporter for traces: {endpoint}"); - if crate::otlp::current_tokio_runtime_is_multi_thread() { - let protocol = match protocol { - OtelHttpProtocol::Binary => Protocol::HttpBinary, - OtelHttpProtocol::Json => Protocol::HttpJson, - }; - - let mut exporter_builder = SpanExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_protocol(protocol) - .with_headers(headers); - - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, - headers_helper, - )?; - exporter_builder = exporter_builder.with_http_client(client); - - let processor = TokioBatchSpanProcessor::builder( - crate::network_policy::PolicyExporter { - exporter: exporter_builder.build()?, - policy: factory.network_policy().clone(), - }, - runtime::Tokio, - ) - .build(); - - return Ok(tracer_provider_builder(resource, span_attributes) - .with_span_processor(processor) - .build()); - } - let protocol = match protocol { OtelHttpProtocol::Binary => Protocol::HttpBinary, OtelHttpProtocol::Json => Protocol::HttpJson, @@ -707,18 +673,39 @@ fn build_tracer_provider( .with_protocol(protocol) .with_headers(headers); - if headers_helper.is_some() || factory.network_policy().is_managed() { - let client = crate::otlp::build_async_http_client( - factory, - tls.as_ref(), - OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, - headers_helper, - )?; - exporter_builder = exporter_builder.with_http_client(client); - } else if let Some(tls) = tls.as_ref() { - let client = - crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)?; - exporter_builder = exporter_builder.with_http_client(client); + if E::CONFIGURE_HTTP_CLIENT { + let use_tokio_processor = crate::otlp::current_tokio_runtime_is_multi_thread(); + if use_tokio_processor + || headers_helper.is_some() + || factory.network_policy().is_managed() + { + let client = crate::otlp::build_async_http_client( + factory, + tls.as_ref(), + OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, + headers_helper, + )?; + exporter_builder = exporter_builder.with_http_client(client); + } else if let Some(tls) = tls.as_ref() { + let client = + crate::otlp::build_http_client(tls, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)?; + exporter_builder = exporter_builder.with_http_client(client); + } + + if use_tokio_processor { + let processor = TokioBatchSpanProcessor::builder( + crate::network_policy::PolicyExporter { + exporter: exporter_builder.build()?, + policy: factory.network_policy().clone(), + }, + runtime::Tokio, + ) + .build(); + + return Ok(tracer_provider_builder(resource, span_attributes) + .with_span_processor(processor) + .build()); + } } exporter_builder.build()? @@ -761,7 +748,6 @@ mod tests { use opentelemetry::trace::Tracer as _; use opentelemetry_sdk::metrics::InMemoryMetricExporter; use pretty_assertions::assert_eq; - use std::path::PathBuf; #[test] fn resource_attributes_include_host_name_when_present() { @@ -999,7 +985,6 @@ mod tests { environment: "test".to_string(), service_name: "codex-test".to_string(), service_version: "0.0.0".to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::None, metrics_exporter: OtelExporter::None, diff --git a/codex-rs/otel/src/provider/exporters.rs b/codex-rs/otel/src/provider/exporters.rs new file mode 100644 index 0000000000..5925d0d7de --- /dev/null +++ b/codex-rs/otel/src/provider/exporters.rs @@ -0,0 +1,103 @@ +//! Compile-time exporter selection for providers that only send one signal over HTTP. + +use super::OtelProvider; +use crate::config::OtelExporter; +use crate::config::OtelHttpProtocol; +use crate::config::OtelSettings; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::error::Error; +use std::marker::PhantomData; + +/// Selects the builders each provider needs so the linker can drop the others. +pub(crate) trait ExporterScope { + const ALL: bool = false; + const TRACES: bool = Self::ALL; + const METRICS: bool = Self::ALL; + const CONFIGURE_HTTP_CLIENT: bool = true; +} + +pub(crate) struct AllExporters; +impl ExporterScope for AllExporters { + const ALL: bool = true; +} + +pub(super) struct HttpTraces; +impl ExporterScope for HttpTraces { + const TRACES: bool = true; +} + +pub(super) struct HttpMetrics; +impl ExporterScope for HttpMetrics { + const METRICS: bool = true; +} + +struct SdkDefault(PhantomData); +impl ExporterScope for SdkDefault { + const TRACES: bool = E::TRACES; + const METRICS: bool = E::METRICS; + const CONFIGURE_HTTP_CLIENT: bool = false; +} + +/// Identifies a service that exports a single signal using the OTLP SDK's default HTTP client. +pub struct BlockingHttpService<'a> { + pub environment: &'a str, + pub name: &'a str, + pub version: &'a str, +} + +/// Destinations supported by the blocking HTTP metrics provider. +pub enum BlockingMetricsDestination<'a> { + Statsig, + OtlpJson(&'a str), +} + +impl BlockingHttpService<'_> { + fn json_exporter(endpoint: &str) -> OtelExporter { + OtelExporter::OtlpHttp { + endpoint: endpoint.to_string(), + headers: HashMap::new(), + protocol: OtelHttpProtocol::Json, + tls: None, + } + } + + fn settings(&self) -> OtelSettings { + OtelSettings { + http_client_factory: codex_http_client::HttpClientFactory::new( + codex_http_client::OutboundProxyPolicy::ReqwestDefault, + ), + headers_helper: None, + environment: self.environment.to_string(), + service_name: self.name.to_string(), + service_version: self.version.to_string(), + exporter: OtelExporter::None, + trace_exporter: OtelExporter::None, + metrics_exporter: OtelExporter::None, + runtime_metrics: false, + span_attributes: HashMap::new(), + tracestate: BTreeMap::new(), + } + } + + /// Export traces to an OTLP/HTTP JSON endpoint using the dedicated batch processor. + pub fn traces(&self, endpoint: &str) -> Result> { + let mut settings = self.settings(); + settings.trace_exporter = Self::json_exporter(endpoint); + OtelProvider::try_new_with_exporters::>(&settings)? + .ok_or_else(|| "OTLP/HTTP trace exporter was unexpectedly disabled".into()) + } + + /// Export metrics using the SDK's periodic reader. + pub fn metrics( + &self, + destination: BlockingMetricsDestination<'_>, + ) -> Result, Box> { + let mut settings = self.settings(); + settings.metrics_exporter = match destination { + BlockingMetricsDestination::Statsig => OtelExporter::Statsig, + BlockingMetricsDestination::OtlpJson(endpoint) => Self::json_exporter(endpoint), + }; + OtelProvider::try_new_with_exporters::>(&settings) + } +} diff --git a/codex-rs/otel/tests/suite/buffered_operations_tests.rs b/codex-rs/otel/tests/suite/buffered_operations_tests.rs index d9dcf9ce3b..45925fe574 100644 --- a/codex-rs/otel/tests/suite/buffered_operations_tests.rs +++ b/codex-rs/otel/tests/suite/buffered_operations_tests.rs @@ -86,7 +86,6 @@ fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown() environment: "test".to_string(), service_name: "test".to_string(), service_version: "1".to_string(), - codex_home: ".".into(), exporter: OtelExporter::None, trace_exporter: OtelExporter::OtlpHttp { endpoint: "http://127.0.0.1:1/v1/traces".to_string(), diff --git a/codex-rs/otel/tests/suite/otel_headers_helper.rs b/codex-rs/otel/tests/suite/otel_headers_helper.rs index 64426d5112..b7eb39d8e9 100644 --- a/codex-rs/otel/tests/suite/otel_headers_helper.rs +++ b/codex-rs/otel/tests/suite/otel_headers_helper.rs @@ -64,6 +64,7 @@ fn check_all_signals(protocol: OtelHttpProtocol, managed_logs: bool) { "cat headers.json" }; let helper = OtelHeadersHelper { + codex_home: dir.path().to_path_buf(), managed: false, command: format!("echo invocation >> calls && {command}"), refresh_interval: Duration::from_secs(3600), @@ -77,7 +78,6 @@ fn check_all_signals(protocol: OtelHttpProtocol, managed_logs: bool) { environment: "test".to_string(), service_name: "otel-helper-test".to_string(), service_version: "test".to_string(), - codex_home: dir.path().to_path_buf(), exporter: exporter("logs"), trace_exporter: exporter("traces"), metrics_exporter: exporter("metrics"), diff --git a/codex-rs/otel/tests/suite/otlp_http_loopback.rs b/codex-rs/otel/tests/suite/otlp_http_loopback.rs index e8f92ffde9..75f429bdfd 100644 --- a/codex-rs/otel/tests/suite/otlp_http_loopback.rs +++ b/codex-rs/otel/tests/suite/otlp_http_loopback.rs @@ -1,5 +1,7 @@ use codex_http_client::HttpClientFactory; use codex_http_client::OutboundProxyPolicy; +use codex_otel::BlockingHttpService; +use codex_otel::BlockingMetricsDestination; use codex_otel::EXEC_SERVER_CLIENT_REQUEST_COUNT_METRIC; use codex_otel::OtelExporter; use codex_otel::OtelHttpProtocol; @@ -16,7 +18,6 @@ use std::io::Read as _; use std::io::Write as _; use std::net::TcpListener; use std::net::TcpStream; -use std::path::PathBuf; use std::sync::Mutex; use std::sync::mpsc; use std::thread; @@ -139,6 +140,14 @@ fn read_http_request( Ok((path, headers, body_bytes)) } +fn blocking_service() -> BlockingHttpService<'static> { + BlockingHttpService { + environment: "test", + name: "codex-cli", + version: env!("CARGO_PKG_VERSION"), + } +} + fn write_http_response(stream: &mut TcpStream, status: &str) -> std::io::Result<()> { let response = format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); stream.write_all(response.as_bytes())?; @@ -206,27 +215,12 @@ fn otlp_http_exporter_honors_cumulative_temporality_env() -> Result<()> { let _ = tx.send(captured); }); - let provider = OtelProvider::try_new_http_metrics(&OtelSettings { - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - headers_helper: None, - exporter: OtelExporter::None, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/metrics"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .expect("set up a metrics-only provider") - .expect("metrics enabled"); + let provider = blocking_service() + .metrics(BlockingMetricsDestination::OtlpJson(&format!( + "http://{addr}/v1/metrics" + ))) + .expect("set up a metrics-only provider") + .expect("metrics enabled"); assert!(provider.logger.is_none()); assert!(provider.tracer_provider.is_none()); let metrics = provider.metrics().expect("metrics client"); @@ -417,7 +411,6 @@ fn otlp_http_exporter_sends_logs_to_collector() environment: "test".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::OtlpHttp { endpoint: format!("http://{addr}/v1/logs"), headers: HashMap::new(), @@ -478,7 +471,6 @@ fn otel_provider_rejects_header_unsafe_configured_tracestate() { environment: "test".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::OtlpHttp { endpoint: "http://127.0.0.1:1/v1/traces".to_string(), @@ -545,7 +537,6 @@ fn otlp_http_exporter_sends_traces_to_collector() environment: "test".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::OtlpHttp { endpoint: format!("http://{addr}/v1/traces"), @@ -664,7 +655,6 @@ async fn otlp_http_exporter_sends_traces_to_collector_with_bounded_shutdown_in_t environment: "test".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::OtlpHttp { endpoint: format!("http://{addr}/v1/traces"), @@ -794,7 +784,6 @@ fn otlp_http_exporter_times_out_when_collector_stalls_during_bounded_shutdown() environment: "test".to_string(), service_name: "codex-cli".to_string(), service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), exporter: OtelExporter::None, trace_exporter: OtelExporter::OtlpHttp { endpoint: format!("http://{addr}/v1/traces"), @@ -889,27 +878,9 @@ fn otlp_http_exporter_sends_traces_to_collector_in_current_thread_tokio_runtime( .expect("current-thread runtime"); let result = runtime.block_on(async move { - let otel = OtelProvider::try_new_http_traces(&OtelSettings { - headers_helper: None, - http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), - environment: "test".to_string(), - service_name: "codex-cli".to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: PathBuf::from("."), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::OtlpHttp { - endpoint: format!("http://{addr}/v1/traces"), - headers: HashMap::new(), - protocol: OtelHttpProtocol::Json, - tls: None, - }, - metrics_exporter: OtelExporter::None, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) - .map_err(|err| err.to_string())? - .expect("otel provider"); + let otel = blocking_service() + .traces(&format!("http://{addr}/v1/traces")) + .map_err(|err| err.to_string())?; let tracing_layer = otel.tracing_layer().expect("tracing layer"); let subscriber = tracing_subscriber::registry().with(tracing_layer); diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.toml index 8c7858782e..1de8800d90 100644 --- a/codex-rs/windows-sandbox-rs/Cargo.toml +++ b/codex-rs/windows-sandbox-rs/Cargo.toml @@ -27,7 +27,6 @@ workspace = true [dependencies] codex-utils-process = { workspace = true } -codex-http-client = { workspace = true } anyhow = "1.0" base64 = { workspace = true } chrono = { version = "0.4.42", default-features = false, features = [ diff --git a/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs index c4e86584cb..74b398ab89 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_provisioning.rs @@ -814,7 +814,6 @@ fn provision_sandbox(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> let offline_sid_str = string_from_sid_bytes(&offline_sid).map_err(anyhow::Error::msg)?; configure_offline_sandbox_network(payload, &offline_sid_str, log)?; let wfp_result = install_wfp_filters( - &payload.codex_home, &payload.offline_username, payload.otel.as_ref(), |message| { diff --git a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs index bee113ddac..e71d581603 100644 --- a/codex-rs/windows-sandbox-rs/src/wfp_setup.rs +++ b/codex-rs/windows-sandbox-rs/src/wfp_setup.rs @@ -1,13 +1,10 @@ use crate::install_wfp_filters_for_account; use crate::setup_error::sanitize_setup_metric_tag_value; use anyhow::Result; -use codex_otel::OtelExporter; +use codex_otel::BlockingHttpService; +use codex_otel::BlockingMetricsDestination; use codex_otel::OtelProvider; -use codex_otel::OtelSettings; use codex_otel::StatsigMetricsSettings; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::path::Path; const WFP_SETUP_SERVICE_NAME: &str = "codex-windows-sandbox-setup"; const WFP_SETUP_SUCCESS_METRIC: &str = "codex.windows_sandbox.wfp_setup_success"; @@ -37,7 +34,6 @@ fn panic_payload_to_string(panic_payload: Box) -> Stri } fn build_wfp_metrics_provider( - codex_home: &Path, otel: Option<&StatsigMetricsSettings>, ) -> Result> { let Some(otel) = otel else { @@ -47,31 +43,20 @@ fn build_wfp_metrics_provider( // depends on this crate, so the parent process passes only the resolved // Statsig environment in the elevation payload. Other exporters are // intentionally omitted from this helper path. - OtelProvider::try_new_http_metrics(&OtelSettings { - headers_helper: None, - http_client_factory: codex_http_client::HttpClientFactory::new( - codex_http_client::OutboundProxyPolicy::ReqwestDefault, - ), - environment: otel.environment.clone(), - service_name: WFP_SETUP_SERVICE_NAME.to_string(), - service_version: env!("CARGO_PKG_VERSION").to_string(), - codex_home: codex_home.to_path_buf(), - exporter: OtelExporter::None, - trace_exporter: OtelExporter::None, - metrics_exporter: OtelExporter::Statsig, - runtime_metrics: false, - span_attributes: HashMap::new(), - tracestate: BTreeMap::new(), - }) + BlockingHttpService { + environment: &otel.environment, + name: WFP_SETUP_SERVICE_NAME, + version: env!("CARGO_PKG_VERSION"), + } + .metrics(BlockingMetricsDestination::Statsig) .map_err(|err| anyhow::anyhow!("failed to initialize WFP setup metrics provider: {err}")) } fn emit_wfp_setup_metric( - codex_home: &Path, otel: Option<&StatsigMetricsSettings>, metric: &WfpSetupMetric, ) -> Result<()> { - let Some(provider) = build_wfp_metrics_provider(codex_home, otel)? else { + let Some(provider) = build_wfp_metrics_provider(otel)? else { return Ok(()); }; if let Some(metrics) = provider.metrics() { @@ -103,7 +88,6 @@ fn emit_wfp_setup_metric( } fn emit_wfp_setup_metric_safely( - codex_home: &Path, otel: Option<&StatsigMetricsSettings>, offline_username: &str, metric: &WfpSetupMetric, @@ -112,7 +96,7 @@ fn emit_wfp_setup_metric_safely( F: FnMut(&str), { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - emit_wfp_setup_metric(codex_home, otel, metric) + emit_wfp_setup_metric(otel, metric) })); match result { Ok(Ok(())) => {} @@ -129,7 +113,6 @@ fn emit_wfp_setup_metric_safely( } pub fn install_wfp_filters( - codex_home: &Path, offline_username: &str, otel: Option<&StatsigMetricsSettings>, mut log: F, @@ -175,7 +158,7 @@ where } }; - emit_wfp_setup_metric_safely(codex_home, otel, offline_username, &metric, &mut log); + emit_wfp_setup_metric_safely(otel, offline_username, &metric, &mut log); match metric.error { Some(error) => Err(anyhow::anyhow!(error)), None => Ok(()),