Skip to main content

mz_ore/
tracing.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Tracing utilities.
17//!
18//! This module contains application tracing utilities built on top of the
19//! [`tracing`] and [`opentelemetry`] libraries. The key exports are:
20//!
21//!  * The **[`configure`]** function, which configures the `tracing` and
22//!    `opentelemetry` crates with sensible defaults and should be called during
23//!    initialization of every Materialize binary.
24//!
25//!  * The **[`OpenTelemetryContext`]** type, which carries a tracing span
26//!    across thread or task boundaries within a process.
27
28use std::collections::BTreeMap;
29use std::hash::{Hash, Hasher};
30use std::io;
31use std::io::IsTerminal;
32use std::str::FromStr;
33use std::sync::LazyLock;
34use std::sync::atomic::{AtomicU64, Ordering};
35use std::sync::{Arc, Mutex, OnceLock};
36use std::time::Duration;
37
38#[cfg(feature = "tokio-console")]
39use console_subscriber::ConsoleLayer;
40use derivative::Derivative;
41use http::HeaderMap;
42use hyper_util::client::legacy::connect::HttpConnector;
43use opentelemetry::propagation::{Extractor, Injector};
44use opentelemetry::trace::TracerProvider;
45use opentelemetry::{KeyValue, global};
46use opentelemetry_otlp::WithTonicConfig;
47use opentelemetry_sdk::propagation::TraceContextPropagator;
48use opentelemetry_sdk::runtime::Tokio;
49use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor;
50use opentelemetry_sdk::{Resource, trace};
51use prometheus::IntCounter;
52use tonic::metadata::MetadataMap;
53use tonic::transport::Endpoint;
54use tracing::{Event, Level, Span, Subscriber, warn};
55#[cfg(feature = "capture")]
56use tracing_capture::{CaptureLayer, SharedStorage};
57use tracing_opentelemetry::OpenTelemetrySpanExt;
58use tracing_subscriber::filter::Directive;
59use tracing_subscriber::fmt::format::{Writer, format};
60use tracing_subscriber::fmt::{self, FmtContext, FormatEvent, FormatFields};
61use tracing_subscriber::layer::{Layer, SubscriberExt};
62use tracing_subscriber::registry::LookupSpan;
63use tracing_subscriber::util::SubscriberInitExt;
64use tracing_subscriber::{EnvFilter, Registry, reload};
65
66use crate::metric;
67use crate::metrics::MetricsRegistry;
68#[cfg(feature = "tokio-console")]
69use crate::netio::SocketAddr;
70use crate::now::{EpochMillis, NowFn, SYSTEM_TIME};
71
72/// Application tracing configuration.
73///
74/// See the [`configure`] function for details.
75#[derive(Derivative)]
76#[derivative(Debug)]
77pub struct TracingConfig<F> {
78    /// The name of the service.
79    pub service_name: &'static str,
80    /// Configuration of the stderr log.
81    pub stderr_log: StderrLogConfig,
82    /// Optional configuration of the [`opentelemetry`] library.
83    pub opentelemetry: Option<OpenTelemetryConfig>,
84    /// Optional configuration for the [Tokio console] integration.
85    ///
86    /// [Tokio console]: https://github.com/tokio-rs/console
87    #[cfg_attr(nightly_doc_features, doc(cfg(feature = "tokio-console")))]
88    #[cfg(feature = "tokio-console")]
89    pub tokio_console: Option<TokioConsoleConfig>,
90    /// Optional configuration for capturing spans during tests.
91    #[cfg(feature = "capture")]
92    #[derivative(Debug = "ignore")]
93    pub capture: Option<SharedStorage>,
94    /// Optional Sentry configuration.
95    pub sentry: Option<SentryConfig<F>>,
96    /// The version of this build of the service.
97    pub build_version: &'static str,
98    /// The commit SHA of this build of the service.
99    pub build_sha: &'static str,
100    /// Registry for prometheus metrics.
101    pub registry: MetricsRegistry,
102}
103
104/// Configures Sentry reporting.
105#[derive(Debug, Clone)]
106pub struct SentryConfig<F> {
107    /// Sentry data source name to submit events to.
108    pub dsn: String,
109    /// The environment name to report to Sentry.
110    ///
111    /// If unset, the Sentry SDK will attempt to read the value from the
112    /// `SENTRY_ENVIRONMENT` environment variable.
113    pub environment: Option<String>,
114    /// Additional tags to include on each Sentry event/exception.
115    pub tags: BTreeMap<String, String>,
116    /// A filter that classifies events before sending them to Sentry.
117    pub event_filter: F,
118}
119
120/// Configures the stderr log.
121#[derive(Debug)]
122pub struct StderrLogConfig {
123    /// The format in which to emit messages.
124    pub format: StderrLogFormat,
125    /// A filter which determines which events are emitted to the log.
126    pub filter: EnvFilter,
127}
128
129/// Specifies the format of a stderr log message.
130#[derive(Debug, Clone)]
131pub enum StderrLogFormat {
132    /// Format as human readable, optionally colored text.
133    ///
134    /// Best suited for direct human consumption in a terminal.
135    Text {
136        /// An optional prefix for each log message.
137        prefix: Option<String>,
138    },
139    /// Format as JSON (in reality, JSONL).
140    ///
141    /// Best suited for ingestion in structured logging aggregators.
142    Json,
143}
144
145/// Configuration for the [`opentelemetry`] library.
146#[derive(Debug)]
147pub struct OpenTelemetryConfig {
148    /// The [OTLP/HTTP] endpoint to export OpenTelemetry data to.
149    ///
150    /// [OTLP/HTTP]: https://github.com/open-telemetry/opentelemetry-specification/blob/b13c1648bae16323868a5caf614bc10c917cc6ca/specification/protocol/otlp.md#otlphttp
151    pub endpoint: String,
152    /// Additional headers to send with every request to the endpoint.
153    pub headers: HeaderMap,
154    /// A filter which determines which events are exported.
155    pub filter: EnvFilter,
156    /// How many spans can be queued before dropping.
157    pub max_batch_queue_size: usize,
158    /// How many spans to process in a single batch
159    pub max_export_batch_size: usize,
160    /// How many concurrent export tasks to allow.
161    /// More tasks can lead to more memory consumed by the exporter.
162    pub max_concurrent_exports: usize,
163    /// Delay between consecutive batch exports.
164    pub batch_scheduled_delay: Duration,
165    /// How long to wait for a batch to be sent before dropping it.
166    pub max_export_timeout: Duration,
167    /// `opentelemetry::sdk::resource::Resource` to include with all
168    /// traces.
169    pub resource: Resource,
170}
171
172/// Configuration of the [Tokio console] integration.
173///
174/// [Tokio console]: https://github.com/tokio-rs/console
175#[cfg_attr(nightly_doc_features, doc(cfg(feature = "tokio-console")))]
176#[cfg(feature = "tokio-console")]
177#[derive(Debug, Clone)]
178pub struct TokioConsoleConfig {
179    /// The address on which to listen for Tokio console connections.
180    ///
181    /// See [`console_subscriber::Builder::server_addr`].
182    pub listen_addr: SocketAddr,
183    /// How frequently to publish updates to clients.
184    ///
185    /// See [`console_subscriber::Builder::publish_interval`].
186    pub publish_interval: Duration,
187    /// How long data is retained for completed tasks.
188    ///
189    /// See [`console_subscriber::Builder::retention`].
190    pub retention: Duration,
191}
192
193type Reloader = Arc<dyn Fn(EnvFilter, Vec<Directive>) -> Result<(), anyhow::Error> + Send + Sync>;
194type DirectiveReloader = Arc<dyn Fn(Vec<Directive>) -> Result<(), anyhow::Error> + Send + Sync>;
195
196/// A handle to the tracing infrastructure configured with [`configure`].
197#[derive(Clone)]
198pub struct TracingHandle {
199    stderr_log: Reloader,
200    opentelemetry: Reloader,
201    sentry: DirectiveReloader,
202}
203
204impl TracingHandle {
205    /// Creates a inoperative tracing handle.
206    ///
207    /// Primarily useful in tests.
208    pub fn disabled() -> TracingHandle {
209        TracingHandle {
210            stderr_log: Arc::new(|_, _| Ok(())),
211            opentelemetry: Arc::new(|_, _| Ok(())),
212            sentry: Arc::new(|_| Ok(())),
213        }
214    }
215
216    /// Dynamically reloads the stderr log filter.
217    pub fn reload_stderr_log_filter(
218        &self,
219        filter: EnvFilter,
220        defaults: Vec<Directive>,
221    ) -> Result<(), anyhow::Error> {
222        (self.stderr_log)(filter, defaults)
223    }
224
225    /// Dynamically reloads the OpenTelemetry log filter.
226    pub fn reload_opentelemetry_filter(
227        &self,
228        filter: EnvFilter,
229        defaults: Vec<Directive>,
230    ) -> Result<(), anyhow::Error> {
231        (self.opentelemetry)(filter, defaults)
232    }
233
234    /// Dynamically reloads the additional sentry directives.
235    pub fn reload_sentry_directives(&self, defaults: Vec<Directive>) -> Result<(), anyhow::Error> {
236        (self.sentry)(defaults)
237    }
238}
239
240impl std::fmt::Debug for TracingHandle {
241    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
242        f.debug_struct("TracingHandle").finish_non_exhaustive()
243    }
244}
245
246// Note that the following defaults are used on startup, regardless of the
247// parameters in LaunchDarkly. If we need to, we can add cli flags to control
248// then going forward.
249
250/// By default we turn off tracing from the following crates, because they
251/// have error spans which are noisy.
252///
253/// Note: folks should feel free to add more crates here if we find more
254/// with long lived Spans.
255pub const LOGGING_DEFAULTS_STR: [&str; 2] = [
256    "kube_client::client::builder=off",
257    // aws_config is very noisy at the INFO level by default.
258    // It logs every time it successfully loads credentials.
259    "aws_config::profile::credentials=off",
260];
261/// Same as [`LOGGING_DEFAULTS_STR`], but structured as [`Directive`]s.
262pub static LOGGING_DEFAULTS: LazyLock<Vec<Directive>> = LazyLock::new(|| {
263    LOGGING_DEFAULTS_STR
264        .into_iter()
265        .map(|directive| Directive::from_str(directive).expect("valid directive"))
266        .collect()
267});
268/// By default we turn off tracing from the following crates, because they
269/// have long-lived Spans, which OpenTelemetry does not handle well.
270///
271/// Note: folks should feel free to add more crates here if we find more
272/// with long lived Spans.
273pub const OPENTELEMETRY_DEFAULTS_STR: [&str; 2] = ["h2=off", "hyper=off"];
274/// Same as [`OPENTELEMETRY_DEFAULTS_STR`], but structured as [`Directive`]s.
275pub static OPENTELEMETRY_DEFAULTS: LazyLock<Vec<Directive>> = LazyLock::new(|| {
276    OPENTELEMETRY_DEFAULTS_STR
277        .into_iter()
278        .map(|directive| Directive::from_str(directive).expect("valid directive"))
279        .collect()
280});
281
282/// By default we turn off tracing from the following crates, because they
283/// have error spans which are noisy.
284pub const SENTRY_DEFAULTS_STR: [&str; 2] =
285    ["kube_client::client::builder=off", "mysql_async::conn=off"];
286/// Same as [`SENTRY_DEFAULTS_STR`], but structured as [`Directive`]s.
287pub static SENTRY_DEFAULTS: LazyLock<Vec<Directive>> = LazyLock::new(|| {
288    SENTRY_DEFAULTS_STR
289        .into_iter()
290        .map(|directive| Directive::from_str(directive).expect("valid directive"))
291        .collect()
292});
293
294/// The [`GLOBAL_SUBSCRIBER`] type.
295type GlobalSubscriber = Arc<dyn Subscriber + Send + Sync + 'static>;
296
297/// An [`Arc`] of the tracing [`Subscriber`] constructed and initialized in
298/// [`configure`]. The value is written when [`configure`] runs.
299pub static GLOBAL_SUBSCRIBER: OnceLock<GlobalSubscriber> = OnceLock::new();
300
301/// Enables application tracing via the [`tracing`] and [`opentelemetry`]
302/// libraries.
303///
304/// The `tracing` library is configured to emit events as textual log lines to
305/// stderr. [`StderrLogConfig`] offer a small degree of control over this
306/// behavior.
307///
308/// If the `opentelemetry` parameter is `Some`, the `tracing` library is
309/// additionally configured to export events to an observability backend, like
310/// [Jaeger] or [Honeycomb].
311///
312/// The `tokio_console` parameter enables integration with the [Tokio console].
313/// When enabled, `tracing` events are collected and made available to the Tokio
314/// console via a server running on port
315///
316/// [Jaeger]: https://jaegertracing.io
317/// [Honeycomb]: https://www.honeycomb.io
318/// [Tokio console]: https://github.com/tokio-rs/console
319// Setting up OpenTelemetry in the background requires we are in a Tokio runtime
320// context, hence the `async`.
321#[allow(clippy::unused_async, deprecated)]
322pub async fn configure<F>(config: TracingConfig<F>) -> Result<TracingHandle, anyhow::Error>
323where
324    F: Fn(&tracing::Metadata<'_>) -> sentry_tracing::EventFilter + Send + Sync + 'static,
325{
326    let stderr_log_layer: Box<dyn Layer<Registry> + Send + Sync> = match config.stderr_log.format {
327        StderrLogFormat::Text { prefix } => {
328            // See: https://no-color.org/
329            let no_color = std::env::var_os("NO_COLOR").unwrap_or_else(|| "".into()) != "";
330            Box::new(
331                fmt::layer()
332                    .with_writer(io::stderr)
333                    .event_format(PrefixFormat {
334                        inner: format(),
335                        prefix,
336                    })
337                    .with_ansi(!no_color && io::stderr().is_terminal()),
338            )
339        }
340        StderrLogFormat::Json => Box::new(
341            fmt::layer()
342                .with_writer(io::stderr)
343                .json()
344                .with_current_span(true),
345        ),
346    };
347    let (stderr_log_filter, stderr_log_filter_reloader) = reload::Layer::new({
348        let mut filter = config.stderr_log.filter;
349        for directive in LOGGING_DEFAULTS.iter() {
350            filter = filter.add_directive(directive.clone());
351        }
352        filter
353    });
354    // Add rate limiting for OpenTelemetry internal logs to prevent log spam
355    // when there are issues with the OpenTelemetry pipeline (e.g., channel full,
356    // connection errors). This only affects logs from "opentelemetry*" targets.
357    let otel_rate_limit_filter = OpenTelemetryRateLimitingFilter::new(Duration::from_secs(
358        OPENTELEMETRY_RATE_LIMIT_BACKOFF_SECS,
359    ));
360    // IMPORTANT: The order matters here. The outer filter's `max_level_hint()` is used
361    // to determine the global tracing level. The `otel_rate_limit_filter` doesn't provide
362    // a `max_level_hint()` (defaults to TRACE), so the `stderr_log_filter` (EnvFilter)
363    // must be the outer filter to ensure the correct max level is reported.
364    let stderr_log_layer = stderr_log_layer
365        .with_filter(otel_rate_limit_filter)
366        .with_filter(stderr_log_filter);
367    let stderr_log_reloader = Arc::new(move |mut filter: EnvFilter, defaults: Vec<Directive>| {
368        for directive in &defaults {
369            filter = filter.add_directive(directive.clone());
370        }
371        Ok(stderr_log_filter_reloader.reload(filter)?)
372    });
373
374    let (otel_layer, otel_reloader): (_, Reloader) = if let Some(otel_config) = config.opentelemetry
375    {
376        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
377
378        // Manually set up a rustls-backed, h2, proxied `Channel`,
379        // with the timeout configured according to:
380        // https://docs.rs/opentelemetry-otlp/latest/opentelemetry_otlp/struct.TonicExporterBuilder.html#method.with_channel
381        let mut http = HttpConnector::new();
382        http.enforce_http(false);
383        let connector = hyper_rustls::HttpsConnectorBuilder::new()
384            .with_provider_and_native_roots(rustls::crypto::aws_lc_rs::default_provider())?
385            .https_or_http()
386            .enable_http2()
387            .wrap_connector(http);
388        let channel = Endpoint::from_shared(otel_config.endpoint)?
389            .timeout(opentelemetry_otlp::OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT)
390            // TODO(guswynn): investigate if this should be non-lazy.
391            .connect_with_connector_lazy(connector);
392        let exporter = opentelemetry_otlp::SpanExporter::builder()
393            .with_tonic()
394            .with_channel(channel)
395            .with_metadata(MetadataMap::from_headers(otel_config.headers))
396            .build()?;
397        let batch_config = opentelemetry_sdk::trace::BatchConfigBuilder::default()
398            .with_max_queue_size(otel_config.max_batch_queue_size)
399            .with_max_export_batch_size(otel_config.max_export_batch_size)
400            .with_max_concurrent_exports(otel_config.max_concurrent_exports)
401            .with_scheduled_delay(otel_config.batch_scheduled_delay)
402            .with_max_export_timeout(otel_config.max_export_timeout)
403            .build();
404        let batch_span_processor = BatchSpanProcessor::builder(exporter, Tokio)
405            .with_batch_config(batch_config)
406            .build();
407        let tracer = trace::SdkTracerProvider::builder()
408            .with_resource(
409                Resource::builder()
410                    .with_service_name(config.service_name.to_string())
411                    .with_attributes(
412                        otel_config
413                            .resource
414                            .iter()
415                            .map(|(k, v)| KeyValue::new(k.clone(), v.clone())),
416                        // TODO handle schema url?
417                    )
418                    .build(),
419            )
420            .with_span_processor(batch_span_processor)
421            .with_max_events_per_span(2048)
422            .build()
423            .tracer(config.service_name);
424
425        let (filter, filter_handle) = reload::Layer::new({
426            let mut filter = otel_config.filter;
427            for directive in OPENTELEMETRY_DEFAULTS.iter() {
428                filter = filter.add_directive(directive.clone());
429            }
430            filter
431        });
432        let metrics_layer = MetricsLayer::new(&config.registry);
433        let layer = tracing_opentelemetry::layer()
434            // OpenTelemetry does not handle long-lived Spans well, and they end up continuously
435            // eating memory until OOM. So we set a max number of events that are allowed to be
436            // logged to a Span, once this max is passed, old events will get dropped
437            //
438            // TODO(parker-timmerman|guswynn): make this configurable with LaunchDarkly
439            .with_tracer(tracer)
440            .and_then(metrics_layer)
441            // WARNING, ENTERING SPOOKY ZONE 2.0
442            //
443            // Notice we use `with_filter` here. `and_then` will apply the filter globally.
444            .with_filter(filter);
445        let reloader = Arc::new(move |mut filter: EnvFilter, defaults: Vec<Directive>| {
446            // Re-apply our defaults on reload.
447            for directive in &defaults {
448                filter = filter.add_directive(directive.clone());
449            }
450            Ok(filter_handle.reload(filter)?)
451        });
452        (Some(layer), reloader)
453    } else {
454        let reloader = Arc::new(|_, _| Ok(()));
455        (None, reloader)
456    };
457
458    #[cfg(feature = "tokio-console")]
459    let tokio_console_layer = if let Some(console_config) = config.tokio_console.clone() {
460        let builder = ConsoleLayer::builder()
461            .publish_interval(console_config.publish_interval)
462            .retention(console_config.retention);
463        let builder = match console_config.listen_addr {
464            SocketAddr::Inet(addr) => builder.server_addr(addr),
465            SocketAddr::Unix(addr) => {
466                let path = addr.as_pathname().unwrap().as_ref();
467                builder.server_addr(path)
468            }
469            SocketAddr::Turmoil(_) => unimplemented!(),
470        };
471        Some(builder.spawn())
472    } else {
473        None
474    };
475
476    let (sentry_layer, sentry_reloader): (_, DirectiveReloader) =
477        if let Some(sentry_config) = config.sentry {
478            let mut options = sentry::ClientOptions::default();
479            options.attach_stacktrace = true;
480            options.release = Some(format!("materialize@{0}", config.build_version).into());
481            options.environment = sentry_config.environment.map(Into::into);
482            let guard = sentry::init((sentry_config.dsn, options));
483
484            // Forgetting the guard ensures that the Sentry transport won't shut down for the
485            // lifetime of the process.
486            std::mem::forget(guard);
487
488            sentry::configure_scope(|scope| {
489                scope.set_tag("service_name", config.service_name);
490                scope.set_tag("build_sha", config.build_sha.to_string());
491                for (k, v) in sentry_config.tags {
492                    scope.set_tag(&k, v);
493                }
494            });
495
496            let (filter, filter_handle) = reload::Layer::new({
497                // Please see the comment on `with_filter` below.
498                let mut filter = EnvFilter::new("info");
499                for directive in SENTRY_DEFAULTS.iter() {
500                    filter = filter.add_directive(directive.clone());
501                }
502                filter
503            });
504            let layer = sentry_tracing::layer()
505                .event_filter(sentry_config.event_filter)
506                // WARNING, ENTERING THE SPOOKY ZONE
507                //
508                // While sentry provides an event filter above that maps events to types of sentry events, its `Layer`
509                // implementation does not participate in `tracing`'s level-fast-path implementation, which depends on
510                // a hidden api (<https://github.com/tokio-rs/tracing/blob/b28c9351dd4f34ed3c7d5df88bb5c2e694d9c951/tracing-subscriber/src/layer/mod.rs#L861-L867>)
511                // which is primarily manged by filters (like below). The fast path skips verbose log
512                // (and span) levels that no layer is interested by reading a single atomic. Usually, not implementing this
513                // api means "give me everything, including `trace`, unless you attach a filter to me.
514                //
515                // The curious thing here (and a bug in tracing) is that _some configurations of our layer stack above_,
516                // if you don't have this filter can cause the fast-path to trigger, despite the fact
517                // that the sentry layer would specifically communicating that it wants to see
518                // everything. This bug appears to be related to the presence of a `reload::Layer`
519                // _around a filter, not a layer_, and guswynn is tracking investigating it here:
520                // <https://github.com/MaterializeInc/database-issues/issues/4794>. Because we don't
521                // enable a reload-able filter in CI/locally, but DO in production (the otel layer), it
522                // was once possible to trigger and rely on the fast path in CI, but not notice that it
523                // was disabled in production.
524                //
525                // The behavior of this optimization is now tested in various scenarios (in
526                // `test/tracing`). Regardless, when the upstream bug is fixed/resolved,
527                // we will continue to place this here, as the sentry layer only cares about
528                // events <= INFO, so we want to use the fast-path if no other layer
529                // is interested in high-fidelity events.
530                .with_filter(filter);
531            let reloader = Arc::new(move |defaults: Vec<Directive>| {
532                // Please see the comment on `with_filter` above.
533                let mut filter = EnvFilter::new("info");
534                // Re-apply our defaults on reload.
535                for directive in &defaults {
536                    filter = filter.add_directive(directive.clone());
537                }
538                Ok(filter_handle.reload(filter)?)
539            });
540            (Some(layer), reloader)
541        } else {
542            let reloader = Arc::new(|_| Ok(()));
543            (None, reloader)
544        };
545
546    #[cfg(feature = "capture")]
547    let capture = config.capture.map(|storage| CaptureLayer::new(&storage));
548
549    let stack = tracing_subscriber::registry();
550    let stack = stack.with(stderr_log_layer);
551    #[cfg(feature = "capture")]
552    let stack = stack.with(capture);
553    let stack = stack.with(otel_layer);
554    #[cfg(feature = "tokio-console")]
555    let stack = stack.with(tokio_console_layer);
556    let stack = stack.with(sentry_layer);
557
558    // Set the stack as a global subscriber.
559    assert!(GLOBAL_SUBSCRIBER.set(Arc::new(stack)).is_ok());
560    // Initialize the subscriber.
561    Arc::clone(GLOBAL_SUBSCRIBER.get().unwrap()).init();
562
563    #[cfg(feature = "tokio-console")]
564    if let Some(console_config) = config.tokio_console {
565        let endpoint = match console_config.listen_addr {
566            SocketAddr::Inet(addr) => format!("http://{addr}"),
567            SocketAddr::Unix(addr) => format!("file://localhost{addr}"),
568            SocketAddr::Turmoil(_) => unimplemented!(),
569        };
570        tracing::info!("starting tokio console on {endpoint}");
571    }
572
573    let handle = TracingHandle {
574        stderr_log: stderr_log_reloader,
575        opentelemetry: otel_reloader,
576        sentry: sentry_reloader,
577    };
578
579    Ok(handle)
580}
581
582/// Returns the [`Level`] of a crate from an [`EnvFilter`] by performing an
583/// exact match between `crate` and the original `EnvFilter` directive.
584pub fn crate_level(filter: &EnvFilter, crate_name: &'static str) -> Level {
585    // TODO: implement `would_enable` on `EnvFilter` or equivalent
586    // to avoid having to manually parse out the directives. This
587    // would also significantly broaden the lookups the fn is able
588    // to do (modules, spans, fields, etc).
589
590    let mut default_level = Level::ERROR;
591    // EnvFilter roundtrips through its Display fmt, so it
592    // is safe to split out its individual directives here
593    for directive in format!("{}", filter).split(',') {
594        match directive.split('=').collect::<Vec<_>>().as_slice() {
595            [target, level] => {
596                if *target == crate_name {
597                    match Level::from_str(*level) {
598                        Ok(level) => return level,
599                        Err(err) => warn!("invalid level for {}: {}", target, err),
600                    }
601                }
602            }
603            [token] => match Level::from_str(*token) {
604                Ok(level) => default_level = default_level.max(level),
605                Err(_) => {
606                    // a target without a level is interpreted as trace
607                    if *token == crate_name {
608                        default_level = default_level.max(Level::TRACE);
609                    }
610                }
611            },
612            _ => {}
613        }
614    }
615
616    default_level
617}
618
619/// A wrapper around a [`FormatEvent`] that adds an optional prefix to each
620/// event.
621#[derive(Debug)]
622pub struct PrefixFormat<F> {
623    inner: F,
624    prefix: Option<String>,
625}
626
627impl<F, C, N> FormatEvent<C, N> for PrefixFormat<F>
628where
629    C: Subscriber + for<'a> LookupSpan<'a>,
630    N: for<'a> FormatFields<'a> + 'static,
631    F: FormatEvent<C, N>,
632{
633    fn format_event(
634        &self,
635        ctx: &FmtContext<'_, C, N>,
636        mut writer: Writer<'_>,
637        event: &Event<'_>,
638    ) -> std::fmt::Result {
639        match &self.prefix {
640            None => self.inner.format_event(ctx, writer, event)?,
641            Some(prefix) => {
642                let mut prefix = yansi::Paint::new(prefix);
643                if writer.has_ansi_escapes() {
644                    prefix = prefix.bold();
645                }
646                write!(writer, "{}: ", prefix)?;
647                self.inner.format_event(ctx, writer, event)?;
648            }
649        }
650        Ok(())
651    }
652}
653
654/// An OpenTelemetry context.
655///
656/// Allows associating [`tracing`] spans across task or thread boundaries.
657#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
658pub struct OpenTelemetryContext {
659    inner: BTreeMap<String, String>,
660}
661
662impl OpenTelemetryContext {
663    /// Attaches this `Context` to the current [`tracing`] span,
664    /// as its parent.
665    ///
666    /// If there is not enough information in this `OpenTelemetryContext`
667    /// to create a context, then the current thread's `Context` is used
668    /// defaulting to the default `Context`.
669    pub fn attach_as_parent(&self) {
670        self.attach_as_parent_to(&tracing::Span::current())
671    }
672
673    /// Attaches this `Context` to the given [`tracing`] Span, as its parent.
674    ///
675    /// If there is not enough information in this `OpenTelemetryContext`
676    /// to create a context, then the current thread's `Context` is used
677    /// defaulting to the default `Context`.
678    pub fn attach_as_parent_to(&self, span: &Span) {
679        let parent_cx = global::get_text_map_propagator(|prop| prop.extract(self));
680        let _ = span.set_parent(parent_cx);
681    }
682
683    /// Obtains a `Context` from the current [`tracing`] span.
684    pub fn obtain() -> Self {
685        let mut context = Self::empty();
686        global::get_text_map_propagator(|propagator| {
687            propagator.inject_context(&tracing::Span::current().context(), &mut context)
688        });
689
690        context
691    }
692
693    /// Obtains an empty `Context`.
694    pub fn empty() -> Self {
695        Self {
696            inner: BTreeMap::new(),
697        }
698    }
699}
700
701impl Extractor for OpenTelemetryContext {
702    fn get(&self, key: &str) -> Option<&str> {
703        self.inner.get(&key.to_lowercase()).map(|v| v.as_str())
704    }
705
706    fn keys(&self) -> Vec<&str> {
707        self.inner.keys().map(|k| k.as_str()).collect::<Vec<_>>()
708    }
709}
710
711impl Injector for OpenTelemetryContext {
712    fn set(&mut self, key: &str, value: String) {
713        self.inner.insert(key.to_lowercase(), value);
714    }
715}
716
717impl From<OpenTelemetryContext> for BTreeMap<String, String> {
718    fn from(ctx: OpenTelemetryContext) -> Self {
719        ctx.inner
720    }
721}
722
723impl From<BTreeMap<String, String>> for OpenTelemetryContext {
724    fn from(map: BTreeMap<String, String>) -> Self {
725        Self { inner: map }
726    }
727}
728
729struct MetricsLayer {
730    on_close: IntCounter,
731}
732
733impl MetricsLayer {
734    fn new(registry: &MetricsRegistry) -> Self {
735        MetricsLayer {
736            on_close: registry.register(metric!(
737                name: "mz_otel_on_close",
738                help: "count of on_close events sent to otel",
739            )),
740        }
741    }
742}
743
744impl<S: tracing::Subscriber> Layer<S> for MetricsLayer {
745    fn on_close(&self, _id: tracing::span::Id, _ctx: tracing_subscriber::layer::Context<'_, S>) {
746        self.on_close.inc()
747    }
748}
749
750/// The target prefix for OpenTelemetry internal logs.
751/// OpenTelemetry crates emit logs with targets like "opentelemetry", "opentelemetry_sdk",
752/// "opentelemetry_otlp", etc.
753const OPENTELEMETRY_TARGET_PREFIX: &str = "opentelemetry";
754
755/// Default backoff duration for rate-limiting OpenTelemetry internal logs.
756const OPENTELEMETRY_RATE_LIMIT_BACKOFF_SECS: u64 = 30;
757
758/// A rate-limiting filter that throttles OpenTelemetry internal log messages.
759///
760/// OpenTelemetry can emit a large number of duplicate error messages (e.g., when
761/// the batch processor channel is full or when there are connection issues).
762/// This filter rate-limits these messages to avoid log spam while still ensuring
763/// the errors are visible.
764///
765/// Only logs from OpenTelemetry targets (those starting with "opentelemetry") are
766/// rate-limited. All other logs pass through unchanged.
767#[derive(Debug)]
768pub struct OpenTelemetryRateLimitingFilter {
769    /// How long to suppress duplicate messages from OpenTelemetry.
770    backoff_duration: Duration,
771    /// Tracks the last time each unique message key was logged.
772    /// The key is a hash of (target, message format string).
773    last_logged: Mutex<BTreeMap<u64, EpochMillis>>,
774    /// Counter for the number of suppressed messages.
775    suppressed_count: AtomicU64,
776    /// Function to get the current time (helps with testing).
777    now_fn: NowFn,
778}
779
780impl OpenTelemetryRateLimitingFilter {
781    /// Creates a new rate-limiting filter with the specified backoff duration.
782    ///
783    /// Messages from OpenTelemetry targets will be suppressed if they occur
784    /// more frequently than once per `backoff_duration`.
785    pub fn new(backoff_duration: Duration) -> Self {
786        Self {
787            backoff_duration,
788            last_logged: Mutex::new(BTreeMap::new()),
789            suppressed_count: AtomicU64::new(0),
790            now_fn: SYSTEM_TIME.clone(),
791        }
792    }
793
794    /// Sets a custom time function for testing purposes.
795    #[cfg(test)]
796    fn with_now_fn(mut self, now_fn: NowFn) -> Self {
797        self.now_fn = now_fn;
798        self
799    }
800
801    /// Computes a hash key for the given event metadata.
802    fn compute_key(metadata: &tracing::Metadata<'_>) -> u64 {
803        let mut hasher = std::hash::DefaultHasher::new();
804        metadata.target().hash(&mut hasher);
805        metadata.name().hash(&mut hasher);
806        // Include the file and line if available for more precise deduplication
807        if let Some(file) = metadata.file() {
808            file.hash(&mut hasher);
809        }
810        if let Some(line) = metadata.line() {
811            line.hash(&mut hasher);
812        }
813        hasher.finish()
814    }
815
816    /// Returns true if the event should be logged (not rate-limited).
817    fn should_log(&self, metadata: &tracing::Metadata<'_>) -> bool {
818        // Only rate-limit OpenTelemetry internal logs
819        if !metadata.target().starts_with(OPENTELEMETRY_TARGET_PREFIX) {
820            return true;
821        }
822
823        let key = Self::compute_key(metadata);
824        let now = (self.now_fn)();
825
826        let mut last_logged = self.last_logged.lock().unwrap();
827
828        if let Some(last_time) = last_logged.get(&key) {
829            if Duration::from_millis(now - last_time) < self.backoff_duration {
830                self.suppressed_count.fetch_add(1, Ordering::Relaxed);
831                return false;
832            }
833        }
834
835        last_logged.insert(key, now);
836
837        // Periodically clean up old entries to prevent unbounded growth
838        // Keep entries that are still within the backoff window
839        if last_logged.len() > 1000 {
840            last_logged
841                .retain(|_, time| Duration::from_millis(now - *time) < self.backoff_duration);
842        }
843
844        true
845    }
846
847    /// Returns the number of messages that have been suppressed.
848    pub fn suppressed_count(&self) -> u64 {
849        self.suppressed_count.load(Ordering::Relaxed)
850    }
851}
852
853impl<S> tracing_subscriber::layer::Filter<S> for OpenTelemetryRateLimitingFilter
854where
855    S: tracing::Subscriber + for<'lookup> LookupSpan<'lookup>,
856{
857    // NB: `enabled` must stay non-mutating. tracing-subscriber calls both `enabled`
858    // and then `event_enabled` for every event; if `should_log` ran in both, the
859    // first call would insert the callsite into `last_logged` and the second would
860    // see it within the backoff window and suppress — dropping every OpenTelemetry
861    // event, including the first.
862    fn enabled(
863        &self,
864        _metadata: &tracing::Metadata<'_>,
865        _ctx: &tracing_subscriber::layer::Context<'_, S>,
866    ) -> bool {
867        true
868    }
869
870    fn event_enabled(
871        &self,
872        event: &Event<'_>,
873        _ctx: &tracing_subscriber::layer::Context<'_, S>,
874    ) -> bool {
875        self.should_log(event.metadata())
876    }
877}
878
879#[cfg(test)]
880mod tests {
881    use std::str::FromStr;
882    use tracing::Level;
883    use tracing_subscriber::filter::{EnvFilter, LevelFilter, Targets};
884
885    #[crate::test]
886    fn overriding_targets() {
887        let user_defined = Targets::new().with_target("my_crate", Level::INFO);
888
889        let default = Targets::new().with_target("my_crate", LevelFilter::OFF);
890        assert!(!default.would_enable("my_crate", &Level::INFO));
891
892        // The user_defined filters should override the default
893        let filters = Targets::new()
894            .with_targets(default)
895            .with_targets(user_defined);
896        assert!(filters.would_enable("my_crate", &Level::INFO));
897    }
898
899    #[crate::test]
900    fn crate_level() {
901        // target=level directives only. should default to ERROR if unspecified
902        let filter = EnvFilter::from_str("abc=trace,def=debug").expect("valid");
903        assert_eq!(super::crate_level(&filter, "abc"), Level::TRACE);
904        assert_eq!(super::crate_level(&filter, "def"), Level::DEBUG);
905        assert_eq!(super::crate_level(&filter, "def"), Level::DEBUG);
906        assert_eq!(
907            super::crate_level(&filter, "abc::doesnt::exist"),
908            Level::ERROR
909        );
910        assert_eq!(super::crate_level(&filter, "doesnt::exist"), Level::ERROR);
911
912        // add in a global default
913        let filter = EnvFilter::from_str("abc=trace,def=debug,info").expect("valid");
914        assert_eq!(super::crate_level(&filter, "abc"), Level::TRACE);
915        assert_eq!(
916            super::crate_level(&filter, "abc::doesnt:exist"),
917            Level::INFO
918        );
919        assert_eq!(super::crate_level(&filter, "def"), Level::DEBUG);
920        assert_eq!(super::crate_level(&filter, "nan"), Level::INFO);
921
922        // a directive with mod path doesn't match the top-level crate
923        let filter = EnvFilter::from_str("abc::def::ghi=trace,debug").expect("valid");
924        assert_eq!(super::crate_level(&filter, "abc"), Level::DEBUG);
925        assert_eq!(super::crate_level(&filter, "def"), Level::DEBUG);
926        assert_eq!(
927            super::crate_level(&filter, "gets_the_default"),
928            Level::DEBUG
929        );
930
931        // directives with spans and fields don't match the top-level crate
932        let filter =
933            EnvFilter::from_str("abc[s]=trace,def[s{g=h}]=debug,[{s2}]=debug,info").expect("valid");
934        assert_eq!(super::crate_level(&filter, "abc"), Level::INFO);
935        assert_eq!(super::crate_level(&filter, "def"), Level::INFO);
936        assert_eq!(super::crate_level(&filter, "gets_the_default"), Level::INFO);
937
938        // a bare target without a level is taken as trace
939        let filter = EnvFilter::from_str("abc,info").expect("valid");
940        assert_eq!(super::crate_level(&filter, "abc"), Level::TRACE);
941        assert_eq!(super::crate_level(&filter, "gets_the_default"), Level::INFO);
942        // the contract of `crate_level` is that it only matches top-level crates.
943        // if we had a proper EnvFilter::would_match impl, this assertion should
944        // be Level::TRACE
945        assert_eq!(super::crate_level(&filter, "abc::def"), Level::INFO);
946    }
947
948    #[crate::test]
949    fn otel_rate_limiting_filter_backoff() {
950        use std::sync::Arc;
951        use std::sync::atomic::{AtomicU64, Ordering};
952        use std::time::Duration;
953        use tracing::Callsite;
954
955        use crate::now::NowFn;
956
957        // Create a controllable time source
958        let current_time = Arc::new(AtomicU64::new(0));
959        let time_for_closure = Arc::clone(&current_time);
960        let now_fn: NowFn = NowFn::from(move || time_for_closure.load(Ordering::SeqCst));
961
962        let filter = super::OpenTelemetryRateLimitingFilter::new(Duration::from_millis(100))
963            .with_now_fn(now_fn);
964
965        // Test that key computation is stable
966        static OTEL_CALLSITE: tracing::callsite::DefaultCallsite =
967            tracing::callsite::DefaultCallsite::new(&tracing::Metadata::new(
968                "test_event",
969                "opentelemetry_sdk::trace",
970                Level::WARN,
971                Some(file!()),
972                Some(line!()),
973                Some(module_path!()),
974                tracing::field::FieldSet::new(&[], tracing::callsite::Identifier(&OTEL_CALLSITE)),
975                tracing::metadata::Kind::EVENT,
976            ));
977        let otel_meta = OTEL_CALLSITE.metadata();
978
979        static OTHER_CALLSITE: tracing::callsite::DefaultCallsite =
980            tracing::callsite::DefaultCallsite::new(&tracing::Metadata::new(
981                "test_event",
982                "my_app::module",
983                Level::WARN,
984                Some(file!()),
985                Some(line!()),
986                Some(module_path!()),
987                tracing::field::FieldSet::new(&[], tracing::callsite::Identifier(&OTHER_CALLSITE)),
988                tracing::metadata::Kind::EVENT,
989            ));
990        let other_meta = OTHER_CALLSITE.metadata();
991
992        // Non-OpenTelemetry events should always pass through
993        assert!(filter.should_log(other_meta));
994        assert!(filter.should_log(other_meta));
995        assert!(filter.should_log(other_meta));
996        assert_eq!(filter.suppressed_count(), 0);
997
998        // First OpenTelemetry event should pass through
999        assert!(filter.should_log(otel_meta));
1000        assert_eq!(filter.suppressed_count(), 0);
1001
1002        // Subsequent OpenTelemetry events within backoff should be suppressed
1003        current_time.store(50, Ordering::SeqCst); // 50ms later, still within 100ms backoff
1004        assert!(!filter.should_log(otel_meta));
1005        assert!(!filter.should_log(otel_meta));
1006        assert_eq!(filter.suppressed_count(), 2);
1007
1008        // After backoff, event should pass through again
1009        current_time.store(150, Ordering::SeqCst); // 150ms later, past 100ms backoff
1010        assert!(filter.should_log(otel_meta));
1011        assert_eq!(filter.suppressed_count(), 2);
1012    }
1013}