From 2f7d3aec0b2b8638a99241a60522d5dae23f26be Mon Sep 17 00:00:00 2001 From: andylokandy Date: Sat, 22 Jun 2024 21:25:02 +0800 Subject: [PATCH] fix Signed-off-by: andylokandy --- CHANGELOG.md | 10 ++ minitrace-datadog/Cargo.toml | 4 +- minitrace-futures/Cargo.toml | 4 +- minitrace-futures/src/lib.rs | 15 +-- minitrace-jaeger/Cargo.toml | 4 +- minitrace-macro/Cargo.toml | 4 +- minitrace-macro/src/lib.rs | 26 ++--- minitrace-opentelemetry/Cargo.toml | 4 +- minitrace/Cargo.toml | 16 ++-- minitrace/examples/tail_sampling.rs | 42 ++++++++ minitrace/src/collector/global_collector.rs | 62 ++++++------ minitrace/src/collector/mod.rs | 100 +++++++------------- minitrace/src/lib.rs | 34 ++++--- minitrace/src/local/local_collector.rs | 9 +- minitrace/src/local/local_span.rs | 4 +- minitrace/src/span.rs | 22 +++-- minitrace/src/util/object_pool.rs | 4 +- rustfmt.toml | 2 + test-statically-disable/src/main.rs | 9 +- 19 files changed, 200 insertions(+), 175 deletions(-) create mode 100644 minitrace/examples/tail_sampling.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c8003d5d..322eff68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +## v0.6.7 + +- Add `Config::report_interval`: The background collector working interval. +- Deprecate `Config::batch_report_interval` and `Config::batch_report_max_spans`. +- Fix a performance issue in object-pool which was causing lock racing. + +## v0.6.6 + +- Update to opentelemetry, opentelemetry_sdk, and opentelemetry-otlp. + ## v0.6.5 - Update to opentelemetry 0.22, opentelemetry_sdk 0.22.1, and opentelemetry-otlp: 0.15. diff --git a/minitrace-datadog/Cargo.toml b/minitrace-datadog/Cargo.toml index 0e200a48..994dbb42 100644 --- a/minitrace-datadog/Cargo.toml +++ b/minitrace-datadog/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace-datadog" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -14,7 +14,7 @@ keywords = ["tracing", "span", "datadog", "jaeger", "opentelemetry"] [dependencies] log = "0.4" -minitrace = { version = "0.6.6", path = "../minitrace" } +minitrace = { version = "0.6.7", path = "../minitrace" } reqwest = { version = "0.11", features = ["blocking"] } rmp-serde = "1" serde = { version = "1", features = ["derive"] } diff --git a/minitrace-futures/Cargo.toml b/minitrace-futures/Cargo.toml index bb4ca41b..7b6bcb0a 100644 --- a/minitrace-futures/Cargo.toml +++ b/minitrace-futures/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace-futures" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -14,7 +14,7 @@ keywords = ["tracing", "span", "futures", "jaeger", "opentelemetry"] [dependencies] futures = "0.3" -minitrace = { version = "0.6.6", path = "../minitrace" } +minitrace = { version = "0.6.7", path = "../minitrace" } pin-project-lite = "0.2.13" [dev-dependencies] diff --git a/minitrace-futures/src/lib.rs b/minitrace-futures/src/lib.rs index 4494f44e..b5df0c28 100644 --- a/minitrace-futures/src/lib.rs +++ b/minitrace-futures/src/lib.rs @@ -13,11 +13,12 @@ use pin_project_lite::pin_project; /// An extension trait for [`futures::Stream`] that provides tracing instrument adapters. pub trait StreamExt: futures::Stream + Sized { - /// Binds a [`Span`] to the [`Stream`] that continues to record until the stream is **finished**. + /// Binds a [`Span`] to the [`Stream`] that continues to record until the stream is + /// **finished**. /// - /// In addition, it sets the span as the local parent at every poll so that [`minitrace::local::LocalSpan`] - /// becomes available within the future. Internally, it calls [`Span::set_local_parent`] when - /// the executor polls it. + /// In addition, it sets the span as the local parent at every poll so that + /// [`minitrace::local::LocalSpan`] becomes available within the future. Internally, it + /// calls [`Span::set_local_parent`] when the executor polls it. /// /// # Examples: /// @@ -59,9 +60,9 @@ impl StreamExt for T where T: futures::Stream {} pub trait SinkExt: futures::Sink + Sized { /// Binds a [`Span`] to the [`Sink`] that continues to record until the sink is **closed**. /// - /// In addition, it sets the span as the local parent at every poll so that [`minitrace::local::LocalSpan`] - /// becomes available within the future. Internally, it calls [`Span::set_local_parent`] when - /// the executor polls it. + /// In addition, it sets the span as the local parent at every poll so that + /// [`minitrace::local::LocalSpan`] becomes available within the future. Internally, it + /// calls [`Span::set_local_parent`] when the executor polls it. /// /// # Examples: /// diff --git a/minitrace-jaeger/Cargo.toml b/minitrace-jaeger/Cargo.toml index b4463384..1785e2f1 100644 --- a/minitrace-jaeger/Cargo.toml +++ b/minitrace-jaeger/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace-jaeger" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -14,7 +14,7 @@ keywords = ["tracing", "span", "datadog", "jaeger", "opentelemetry"] [dependencies] log = "0.4" -minitrace = { version = "0.6.6", path = "../minitrace" } +minitrace = { version = "0.6.7", path = "../minitrace" } thrift_codec = "0.3" [dev-dependencies] diff --git a/minitrace-macro/Cargo.toml b/minitrace-macro/Cargo.toml index c97c4b94..1a6358eb 100644 --- a/minitrace-macro/Cargo.toml +++ b/minitrace-macro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace-macro" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -24,7 +24,7 @@ syn = { version = "1.0.84", features = ["full", "parsing", "extra-traits", "proc [dev-dependencies] logcall = "0.1.4" -minitrace = { version = "0.6.6", path = "../minitrace" } +minitrace = { version = "0.6.7", path = "../minitrace" } tokio = { version = "1", features = ["full"] } trybuild = "1" # The procedural macro `trace` only supports async-trait higher than 0.1.52 diff --git a/minitrace-macro/src/lib.rs b/minitrace-macro/src/lib.rs index 6a47a35f..a325fcb5 100644 --- a/minitrace-macro/src/lib.rs +++ b/minitrace-macro/src/lib.rs @@ -3,9 +3,9 @@ //! An attribute macro designed to eliminate boilerplate code for [`minitrace`](https://crates.io/crates/minitrace). #![recursion_limit = "256"] -// Instrumenting the async fn is not as straight forward as expected because `async_trait` rewrites `async fn` -// into a normal fn which returns `Box`, and this stops the macro from distinguishing `async fn` from `fn`. -// The following code reused the `async_trait` probes from [tokio-tracing](https://github.com/tokio-rs/tracing/blob/6a61897a5e834988ad9ac709e28c93c4dbf29116/tracing-attributes/src/expand.rs). +// Instrumenting the async fn is not as straight forward as expected because `async_trait` rewrites +// `async fn` into a normal fn which returns `Box`, and this stops the macro from +// distinguishing `async fn` from `fn`. The following code reused the `async_trait` probes from [tokio-tracing](https://github.com/tokio-rs/tracing/blob/6a61897a5e834988ad9ac709e28c93c4dbf29116/tracing-attributes/src/expand.rs). extern crate proc_macro; @@ -107,21 +107,23 @@ impl Parse for Args { /// An attribute macro designed to eliminate boilerplate code. /// -/// This macro automatically creates a span for the annotated function. The span name defaults to the function -/// name but can be customized by passing a string literal as an argument using the `name` parameter. +/// This macro automatically creates a span for the annotated function. The span name defaults to +/// the function name but can be customized by passing a string literal as an argument using the +/// `name` parameter. /// /// The `#[trace]` attribute requires a local parent context to function correctly. Ensure that -/// the function annotated with `#[trace]` is called within __a local context of a `Span`__, which is -/// established by invoking the `Span::set_local_parent()` method. +/// the function annotated with `#[trace]` is called within __a local context of a `Span`__, which +/// is established by invoking the `Span::set_local_parent()` method. /// /// ## Arguments /// /// * `name` - The name of the span. Defaults to the full path of the function. -/// * `short_name` - Whether to use the function name without path as the span name. Defaults to `false`. -/// * `enter_on_poll` - Whether to enter the span on poll. If set to `false`, `in_span` will be used. -/// Only available for `async fn`. Defaults to `false`. -/// * `properties` - A list of key-value pairs to be added as properties to the span. The value can be -/// a format string, where the function arguments are accessible. Defaults to `{}`. +/// * `short_name` - Whether to use the function name without path as the span name. Defaults to +/// `false`. +/// * `enter_on_poll` - Whether to enter the span on poll. If set to `false`, `in_span` will be +/// used. Only available for `async fn`. Defaults to `false`. +/// * `properties` - A list of key-value pairs to be added as properties to the span. The value can +/// be a format string, where the function arguments are accessible. Defaults to `{}`. /// /// # Examples /// diff --git a/minitrace-opentelemetry/Cargo.toml b/minitrace-opentelemetry/Cargo.toml index 337dadca..b33829fc 100644 --- a/minitrace-opentelemetry/Cargo.toml +++ b/minitrace-opentelemetry/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace-opentelemetry" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -15,7 +15,7 @@ keywords = ["tracing", "span", "datadog", "jaeger", "opentelemetry"] [dependencies] futures = { version = "0.3", features = ["executor"] } log = "0.4" -minitrace = { version = "0.6.6", path = "../minitrace" } +minitrace = { version = "0.6.7", path = "../minitrace" } opentelemetry = { version = "0.23", features = ["trace"] } opentelemetry_sdk = { version = "0.23", features = ["trace"] } diff --git a/minitrace/Cargo.toml b/minitrace/Cargo.toml index 7eda897e..dd88c861 100644 --- a/minitrace/Cargo.toml +++ b/minitrace/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minitrace" -version = "0.6.6" +version = "0.6.7" authors = ["The TiKV Project Authors"] license = "Apache-2.0" edition = "2021" @@ -16,7 +16,7 @@ keywords = ["tracing", "span", "datadog", "jaeger", "opentelemetry"] enable = [] [dependencies] -minitrace-macro = { version = "0.6.6", path = "../minitrace-macro" } +minitrace-macro = { version = "0.6.7", path = "../minitrace-macro" } minstant = "0.1.7" parking_lot = "0.12" pin-project = "1" @@ -26,26 +26,24 @@ rand = "0.8" rtrb = "0.2" [dev-dependencies] -# The procedural macro `trace` only supports async-trait higher than 0.1.52 async-trait = "0.1.52" criterion = { version = "0.5", features = ["html_reports"] } crossbeam = "0.8" env_logger = "0.11" +flume = "0.11.0" futures = "0.3" futures-timer = "3" log = "0.4" logcall = "0.1.4" minitrace = { path = ".", features = ["enable"] } -minitrace-datadog = { version = "0.6.6", path = "../minitrace-datadog" } -minitrace-jaeger = { version = "0.6.6", path = "../minitrace-jaeger" } -minitrace-opentelemetry = { version = "0.6.6", path = "../minitrace-opentelemetry" } +minitrace-datadog = { version = "0.6.7", path = "../minitrace-datadog" } +minitrace-jaeger = { version = "0.6.7", path = "../minitrace-jaeger" } +minitrace-opentelemetry = { version = "0.6.7", path = "../minitrace-opentelemetry" } mockall = "0.12" once_cell = "1" -opentelemetry-otlp = { version = "0.16", features = ["trace"] } -flume = "0.11.0" opentelemetry = { version = "0.23", features = ["trace"] } +opentelemetry-otlp = { version = "0.16", features = ["trace"] } opentelemetry_sdk = { version = "0.23", features = ["trace"] } - rand = "0.8" rustracing = "0.6" serial_test = "3" diff --git a/minitrace/examples/tail_sampling.rs b/minitrace/examples/tail_sampling.rs new file mode 100644 index 00000000..f5d94ed0 --- /dev/null +++ b/minitrace/examples/tail_sampling.rs @@ -0,0 +1,42 @@ +use std::time::Duration; + +use minitrace::collector::Config; +use minitrace::collector::ConsoleReporter; +use minitrace::prelude::*; + +fn main() { + minitrace::set_reporter(ConsoleReporter, Config::default()); + + { + let parent = SpanContext::random(); + let mut root = Span::root("light work", parent); + let _span_guard = root.set_local_parent(); + + expensive_work(Duration::from_millis(50)); + + // Cancel the trace to avoid reporting if it's too short. + if root.elapsed() < Some(Duration::from_millis(100)) { + root.cancel(); + } + }; + + { + let parent = SpanContext::random(); + let mut root = Span::root("heavy work", parent); + let _span_guard = root.set_local_parent(); + + expensive_work(Duration::from_millis(200)); + + // This trace will be reported. + if root.elapsed() < Some(Duration::from_millis(100)) { + root.cancel(); + } + }; + + minitrace::flush(); +} + +#[trace] +fn expensive_work(time: Duration) { + std::thread::sleep(time); +} diff --git a/minitrace/src/collector/global_collector.rs b/minitrace/src/collector/global_collector.rs index fc6fe983..6af6ff61 100644 --- a/minitrace/src/collector/global_collector.rs +++ b/minitrace/src/collector/global_collector.rs @@ -9,7 +9,6 @@ use std::sync::Arc; use minstant::Anchor; use minstant::Instant; -use once_cell::sync::Lazy; use parking_lot::Mutex; use crate::collector::command::CollectCommand; @@ -34,12 +33,12 @@ use crate::util::CollectToken; static NEXT_COLLECT_ID: AtomicUsize = AtomicUsize::new(0); static GLOBAL_COLLECTOR: Mutex> = Mutex::new(None); -static SPSC_RXS: Lazy>>> = Lazy::new(|| Mutex::new(Vec::new())); +static SPSC_RXS: Mutex>> = Mutex::new(Vec::new()); static REPORTER_READY: AtomicBool = AtomicBool::new(false); thread_local! { static COMMAND_SENDER: UnsafeCell> = { - let (tx, rx) = spsc::bounded(102400); + let (tx, rx) = spsc::bounded(10240); register_receiver(rx); UnsafeCell::new(tx) }; @@ -95,15 +94,14 @@ pub fn flush() { #[cfg(not(target_family = "wasm"))] { - // Spawns a new thread to ensure the reporter operates outside the tokio runtime to prevent panic. + // Spawns a new thread to ensure the reporter operates outside the tokio runtime to + // prevent panic. std::thread::Builder::new() .name("minitrace-flush".to_string()) .spawn(move || { - GLOBAL_COLLECTOR - .lock() - .as_mut() - .unwrap() - .handle_commands(true); + if let Some(global_collector) = GLOBAL_COLLECTOR.lock().as_mut() { + global_collector.handle_commands(); + } }) .unwrap() .join() @@ -141,11 +139,12 @@ impl GlobalCollect { // Note that: relationships are not built completely for now so a further job is needed. // - // Every `SpanSet` has its own root spans whose `raw_span.parent_id`s are equal to `SpanId::default()`. + // Every `SpanSet` has its own root spans whose `raw_span.parent_id`s are equal to + // `SpanId::default()`. // // Every root span can have multiple parents where mainly comes from `Span::enter_with_parents`. - // Those parents are recorded into `CollectToken` which has several `CollectTokenItem`s. Look into - // a `CollectTokenItem`, `parent_ids` can be found. + // Those parents are recorded into `CollectToken` which has several `CollectTokenItem`s. Look + // into a `CollectTokenItem`, `parent_ids` can be found. // // For example, we have a `SpanSet::LocalSpansInner` and a `CollectToken` as follow: // @@ -159,7 +158,8 @@ impl GlobalCollect { // | 70 | default | ... | <- root span +------------+------------+ // +------+-----------+-----+ // - // There is a many-to-many mapping. Span#15 has parents Span#7, Span#321 and Span#413, so does Span#70. + // There is a many-to-many mapping. Span#15 has parents Span#7, Span#321 and Span#413, so does + // Span#70. // // So the expected further job mentioned above is: // * Copy `SpanSet` to the same number of copies as `CollectTokenItem`s, one `SpanSet` to one @@ -198,14 +198,14 @@ pub(crate) struct GlobalCollector { reporter: Option>, active_collectors: HashMap, - committed_records: Vec, - last_report: Instant, - // Vectors to be reused by collection loops. They must be empty outside of the `handle_commands` loop. + // Vectors to be reused by collection loops. They must be empty outside of the + // `handle_commands` loop. start_collects: Vec, drop_collects: Vec, commit_collects: Vec, submit_spans: Vec, + committed_records: Vec, } impl GlobalCollector { @@ -217,7 +217,6 @@ impl GlobalCollector { active_collectors: HashMap::new(), committed_records: Vec::new(), - last_report: Instant::now(), start_collects: Vec::new(), drop_collects: Vec::new(), @@ -234,12 +233,10 @@ impl GlobalCollector { .spawn(move || { loop { let begin_instant = Instant::now(); - if let Some(global_collector) = GLOBAL_COLLECTOR.lock().as_mut() { - global_collector.handle_commands(false); - } + GLOBAL_COLLECTOR.lock().as_mut().unwrap().handle_commands(); std::thread::sleep( config - .background_collect_interval + .report_interval .saturating_sub(begin_instant.elapsed()), ); } @@ -248,13 +245,14 @@ impl GlobalCollector { } } - fn handle_commands(&mut self, flush: bool) { + fn handle_commands(&mut self) { object_pool::enable_reuse_in_current_thread(); debug_assert!(self.start_collects.is_empty()); debug_assert!(self.drop_collects.is_empty()); debug_assert!(self.commit_collects.is_empty()); debug_assert!(self.submit_spans.is_empty()); + debug_assert!(self.committed_records.is_empty()); let start_collects = &mut self.start_collects; let drop_collects = &mut self.drop_collects; @@ -283,7 +281,8 @@ impl GlobalCollector { }); } - // If the reporter is not set, global collectior only clears the channel and then dismiss all messages. + // If the reporter is not set, global collectior only clears the channel and then dismiss + // all messages. if self.reporter.is_none() { start_collects.clear(); drop_collects.clear(); @@ -330,8 +329,9 @@ impl GlobalCollector { for item in collect_token.iter() { if let Some(active_collector) = self.active_collectors.get_mut(&item.collect_id) { - // Multiple items in a collect token are built from `Span::enter_from_parents`, - // so relative span cannot be a root span. + // Multiple items in a collect token are built from + // `Span::enter_from_parents`, so relative span + // cannot be a root span. if active_collector.span_count < self.config.max_spans_per_trace.unwrap_or(usize::MAX) { @@ -373,16 +373,8 @@ impl GlobalCollector { } } - if self.last_report.elapsed() > self.config.batch_report_interval - || committed_records.len() > self.config.batch_report_max_spans.unwrap_or(usize::MAX) - || flush - { - self.reporter - .as_mut() - .unwrap() - .report(committed_records.drain(..).as_slice()); - self.last_report = Instant::now(); - } + self.reporter.as_mut().unwrap().report(committed_records); + committed_records.clear(); } } diff --git a/minitrace/src/collector/mod.rs b/minitrace/src/collector/mod.rs index eee56ee5..d460da07 100644 --- a/minitrace/src/collector/mod.rs +++ b/minitrace/src/collector/mod.rs @@ -266,19 +266,20 @@ impl SpanContext { #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Config { pub(crate) max_spans_per_trace: Option, - pub(crate) batch_report_interval: Duration, - pub(crate) batch_report_max_spans: Option, - pub(crate) background_collect_interval: Duration, + pub(crate) report_interval: Duration, pub(crate) report_before_root_finish: bool, } impl Config { - /// A soft limit for the total number of spans and events for a trace, usually used - /// to avoid out-of-memory. + /// Sets a soft limit for the total number of spans and events in a trace, typically + /// used to prevent out-of-memory issues. + /// + /// The default value is `None`. /// /// # Note /// - /// Root span will always be collected. The eventually collected spans may exceed the limit. + /// The root span will always be collected, so the actual number of collected spans + /// may exceed the specified limit. /// /// # Examples /// @@ -295,75 +296,44 @@ impl Config { } } - /// The time duration between two batch reports. - /// - /// The default value is 500 milliseconds. - /// - /// A batch report will be initiated by the earliest of these events: - /// - /// - When the specified time duration between two batch reports is met. - /// - When the number of spans in a batch hits its limit. - /// - /// # Examples - /// - /// ``` - /// use std::time::Duration; - /// - /// use minitrace::collector::Config; - /// - /// let config = Config::default().batch_report_interval(Duration::from_secs(1)); - /// minitrace::set_reporter(minitrace::collector::ConsoleReporter, config); - /// ``` - pub fn batch_report_interval(self, batch_report_interval: Duration) -> Self { - Self { - batch_report_interval, - ..self - } + /// Sets the time duration between two batch reports. + #[deprecated( + since = "0.6.7", + note = "Please use `report_interval` instead. This method is now a no-op." + )] + pub fn batch_report_interval(self, _batch_report_interval: Duration) -> Self { + self } - /// The soft limit for the maximum number of spans in a batch report. - /// - /// A batch report will be initiated by the earliest of these events: - /// - /// - When the specified time duration between two batch reports is met. - /// - When the number of spans in a batch hits its limit. - /// - /// # Note - /// - /// The eventually spans being reported may exceed the limit. - /// - /// # Examples - /// - /// ``` - /// use std::time::Duration; - /// - /// use minitrace::collector::Config; - /// - /// let config = Config::default().batch_report_max_spans(Some(200)); - /// minitrace::set_reporter(minitrace::collector::ConsoleReporter, config); - /// ``` - pub fn batch_report_max_spans(self, batch_report_max_spans: Option) -> Self { - Self { - batch_report_max_spans, - ..self - } + /// Sets the soft limit for the maximum number of spans in a batch report. + #[deprecated( + since = "0.6.7", + note = "Please use `report_interval` instead. This method is now a no-op." + )] + pub fn batch_report_max_spans(self, _batch_report_max_spans: Option) -> Self { + self } - /// The time duration between two background collects. Decrease to reduce the probability - /// of losing spans due to channel full. + /// Sets the time duration between two reports. The reporter will be invoked when the specified + /// duration elapses, even if no spans have been collected. This allows for batching in the + /// reporter. /// - /// Unless you are under very high pressure, and have vitnessed spans being lost, - /// you should not need to change this value. + /// In some scenarios, particularly under high load, you may notice spans being lost. This is + /// likely due to the channel being full during the reporting interval. To mitigate this issue, + /// consider reducing the report interval, potentially down to zero, to prevent losing spans. /// /// The default value is 10 milliseconds. - pub fn background_collector_interval(self, background_collect_interval: Duration) -> Self { + pub fn report_interval(self, report_interval: Duration) -> Self { Self { - background_collect_interval, + report_interval, ..self } } - /// Whether to report the spans before the root span finishes. + /// Configures whether to report spans before the root span finishes. + /// + /// If set to `true`, some spans may be reported before they are canceled, making it + /// difficult to cancel all spans in a trace. /// /// The default value is `false`. /// @@ -387,9 +357,7 @@ impl Default for Config { fn default() -> Self { Self { max_spans_per_trace: None, - batch_report_interval: Duration::from_millis(500), - batch_report_max_spans: None, - background_collect_interval: Duration::from_millis(10), + report_interval: Duration::from_millis(10), report_before_root_finish: false, } } diff --git a/minitrace/src/lib.rs b/minitrace/src/lib.rs index 95adfe5f..c331f53a 100644 --- a/minitrace/src/lib.rs +++ b/minitrace/src/lib.rs @@ -144,11 +144,12 @@ //! //! Sometimes, passing a `Span` through a function to create a child `Span` can be inconvenient. //! We can employ a thread-local approach to avoid an explicit argument passing in the function. -//! In minitrace, [`Span::set_local_parent()`] and [`Span::enter_with_local_parent()`] serve this purpose. +//! In minitrace, [`Span::set_local_parent()`] and [`Span::enter_with_local_parent()`] serve this +//! purpose. //! -//! [`Span::set_local_parent()`] method sets __a local context of the `Span`__ for the current thread. -//! [`Span::enter_with_local_parent()`] accesses the parent `Span` from the local context and creates -//! a child `Span` with it. +//! [`Span::set_local_parent()`] method sets __a local context of the `Span`__ for the current +//! thread. [`Span::enter_with_local_parent()`] accesses the parent `Span` from the local context +//! and creates a child `Span` with it. //! //! ``` //! use minitrace::prelude::*; @@ -224,7 +225,8 @@ //! //! ## Event //! -//! [`Event`] represents a single point in time where something occurred during the execution of a program. +//! [`Event`] represents a single point in time where something occurred during the execution of a +//! program. //! //! An `Event` can be seen as a log record attached to a span. //! ``` @@ -253,8 +255,8 @@ //! //! The attribute-macro [`trace`] helps to reduce boilerplate. //! -//! Note: For successful tracing a function using the [`trace`] macro, the function call should occur -//! within __a local context of a `Span`__. +//! Note: For successful tracing a function using the [`trace`] macro, the function call should +//! occur within __a local context of a `Span`__. //! //! For more detailed usage instructions, please refer to [`trace`]. //! @@ -306,7 +308,9 @@ //! and `minitrace-opentelemetry` are available. //! //! By default, the reporter is triggered every 500 milliseconds. The reporter can also be -//! triggered manually by calling [`flush()`]. See [`Config`] for customizing the reporting behavior. +//! triggered manually by calling [`flush()`]. See [`Config`] for customizing the reporting +//! behavior. +//! //! ``` //! use std::time::Duration; //! @@ -328,16 +332,16 @@ //! - **No Tracing**: If the feature `enable` is not set in the application, `minitrace` will be //! completely optimized away from the final executable binary, achieving zero overhead. //! -//! - **Sample Tracing**: If `enable` is set in the application, but only a small portion -//! of the traces are enabled via [`Span::root()`], while the other portions are started with +//! - **Sample Tracing**: If `enable` is set in the application, but only a small portion of the +//! traces are enabled via [`Span::root()`], while the other portions are started with //! placeholders using [`Span::noop()`]. The overhead in this case is very small - merely an //! integer load, comparison, and jump. //! -//! - **Full Tracing with Tail Sampling**: If `enable` is set in the application, and all -//! traces are enabled, however, only a select few interesting tracing records (e.g., P99) are -//! reported, while normal traces are dismissed by using [`Span::cancel()`] to avoid being -//! reported, the overhead of collecting traces is still very small. This could be useful when -//! you are interested in examining program's tail latency. +//! - **Full Tracing with Tail Sampling**: If `enable` is set in the application, and all traces are +//! enabled, however, only a select few interesting tracing records (e.g., P99) are reported, +//! while normal traces are dismissed by using [`Span::cancel()`] to avoid being reported, the +//! overhead of collecting traces is still very small. This could be useful when you are +//! interested in examining program's tail latency. //! //! - **Full Tracing**: If `enable` is set in the application, and all traces are reported, //! `minitrace` performs 10x to 100x faster than other tracing libraries in this case. diff --git a/minitrace/src/local/local_collector.rs b/minitrace/src/local/local_collector.rs index a16e7075..42e83118 100644 --- a/minitrace/src/local/local_collector.rs +++ b/minitrace/src/local/local_collector.rs @@ -16,11 +16,12 @@ use crate::util::RawSpans; /// A collector to collect [`LocalSpan`]. /// -/// `LocalCollector` allows to collect `LocalSpan` manually without a local parent. The collected `LocalSpan` can later be -/// attached to a parent. +/// `LocalCollector` allows to collect `LocalSpan` manually without a local parent. The collected +/// `LocalSpan` can later be attached to a parent. /// -/// Generally, [`Span`] and `LocalSpan` are sufficient. However, use `LocalCollector` when the span might initiate before its -/// parent span. This is particularly useful for tracing prior tasks that may be obstructing the current request. +/// Generally, [`Span`] and `LocalSpan` are sufficient. However, use `LocalCollector` when the span +/// might initiate before its parent span. This is particularly useful for tracing prior tasks that +/// may be obstructing the current request. /// /// # Examples /// diff --git a/minitrace/src/local/local_span.rs b/minitrace/src/local/local_span.rs index f440ac5f..6b28193c 100644 --- a/minitrace/src/local/local_span.rs +++ b/minitrace/src/local/local_span.rs @@ -24,8 +24,8 @@ struct LocalSpanInner { } impl LocalSpan { - /// Create a new child span associated with the current local span in the current thread, and then - /// it will become the new local parent. + /// Create a new child span associated with the current local span in the current thread, and + /// then it will become the new local parent. /// /// If no local span is active, this function is no-op. /// diff --git a/minitrace/src/span.rs b/minitrace/src/span.rs index 2801b46b..e1bbed7f 100644 --- a/minitrace/src/span.rs +++ b/minitrace/src/span.rs @@ -58,7 +58,8 @@ impl Span { /// Create a new trace and return its root span. /// - /// Once dropped, the root span automatically submits all associated child spans to the reporter. + /// Once dropped, the root span automatically submits all associated child spans to the + /// reporter. /// /// # Examples /// @@ -122,10 +123,12 @@ impl Span { /// Create a new child span associated with multiple parent spans. /// /// This function is particularly useful when a single operation amalgamates multiple requests. - /// It enables the creation of a unique child span that is interconnected with all the parent spans - /// related to the requests, thereby obviating the need to generate individual child spans for each parent span. + /// It enables the creation of a unique child span that is interconnected with all the parent + /// spans related to the requests, thereby obviating the need to generate individual child + /// spans for each parent span. /// - /// The newly created child span, and its children, will have a replica for each trace of parent spans. + /// The newly created child span, and its children, will have a replica for each trace of parent + /// spans. /// /// # Examples /// @@ -190,8 +193,9 @@ impl Span { /// /// This method is used to establish a `Span` as the local parent within the current scope. /// - /// A local parent is necessary for creating a [`LocalSpan`] using [`LocalSpan::enter_with_local_parent()`]. - /// If no local parent is set, `enter_with_local_parent()` will not perform any action. + /// A local parent is necessary for creating a [`LocalSpan`] using + /// [`LocalSpan::enter_with_local_parent()`]. If no local parent is set, + /// `enter_with_local_parent()` will not perform any action. /// /// # Examples /// @@ -270,9 +274,9 @@ impl Span { /// Attach a collection of [`LocalSpan`] instances as child spans to the current span. /// - /// This method allows you to associate previously collected `LocalSpan` instances with the current span. - /// This is particularly useful when the `LocalSpan` instances were initiated before their parent span, - /// and were collected manually using a [`LocalCollector`]. + /// This method allows you to associate previously collected `LocalSpan` instances with the + /// current span. This is particularly useful when the `LocalSpan` instances were initiated + /// before their parent span, and were collected manually using a [`LocalCollector`]. /// /// # Examples /// diff --git a/minitrace/src/util/object_pool.rs b/minitrace/src/util/object_pool.rs index 06d54d14..47bc7d45 100644 --- a/minitrace/src/util/object_pool.rs +++ b/minitrace/src/util/object_pool.rs @@ -21,8 +21,8 @@ fn is_reusable() -> bool { pub struct Pool { // The objects in the pool ready to be reused. - // The mutex should only be visited in the global collector, which is guaranteed by `is_reusable`, - // so it should not have synchronization overhead. + // The mutex should only be visited in the global collector, which is guaranteed by + // `is_reusable`, so it should not have synchronization overhead. objects: Mutex>, init: fn() -> T, reset: fn(&mut T), diff --git a/rustfmt.toml b/rustfmt.toml index 757638be..555ed4f1 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -8,3 +8,5 @@ trailing_comma = "Vertical" overflow_delimited_expr = true format_code_in_doc_comments = true normalize_comments = true +comment_width = 120 +wrap_comments = true diff --git a/test-statically-disable/src/main.rs b/test-statically-disable/src/main.rs index f09af1eb..8ce34bed 100644 --- a/test-statically-disable/src/main.rs +++ b/test-statically-disable/src/main.rs @@ -2,9 +2,11 @@ // The libraries may have tracing instrument embedded in the code for tracing purposes. However, // if the executable does not enable minitrace, it will be statically disabled. This results in -// zero overhead to the libraries, achieved through conditional compilation with the "enable" feature. +// zero overhead to the libraries, achieved through conditional compilation with the "enable" +// feature. // -// The following test is designed to confirm that minitrace compiles when it's statically disabled in the executable. +// The following test is designed to confirm that minitrace compiles when it's statically disabled +// in the executable. use std::time::Duration; @@ -18,9 +20,8 @@ fn main() { minitrace::set_reporter( ConsoleReporter, Config::default() - .batch_report_interval(Duration::from_secs(1)) .max_spans_per_trace(Some(100)) - .batch_report_max_spans(Some(200)) + .report_interval(Duration::from_secs(1)) .report_before_root_finish(true), );