Skip to content

Commit

Permalink
subscriber: unify span traversal (tokio-rs#1431)
Browse files Browse the repository at this point in the history
Fixes tokio-rs#1429 (forwardport from v0.1.x branch)

Implemented as described in tokio-rs#1429, and migrated all internal uses of the
deprecated methods. All tests passed both before and after the migration
(9ec8130).

- Add a new method `SpanRef::scope(&self)` that returns a leaf-to-root
  `Iterator`, including the specified leaf
- Add a new method `Scope::from_root(self)` (where `Scope` is the type
  returned by `SpanRef::scope` defined earlier) that returns a
  root-to-leaf `Iterator` that ends at the current leaf (in other
  words: it's essentially the same as
  `Scope::collect::<Vec<_>>().into_iter().rev()`)
- Deprecate all existing iterators, since they can be replaced by the
  new unified mechanism:
  - `Span::parents` is equivalent to `Span::scope().skip(1)` (although
    the `skip` is typically a bug)
  - `Span::from_root` is equivalent to `Span::scope().skip(1).from_root()`
    (although the `skip` is typically a bug)
  - `Context::scope` is equivalent to
    `Context::lookup_current().scope().from_root()` (although the
    `lookup_current` is sometimes a bug, see also tokio-rs#1428)
  • Loading branch information
nightkr committed Jun 24, 2021
1 parent d92d739 commit 3a5d175
Show file tree
Hide file tree
Showing 13 changed files with 412 additions and 153 deletions.
3 changes: 1 addition & 2 deletions examples/examples/sloggish/sloggish_collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ impl<'a> Visit for Event<'a> {
Style::new().bold().paint(format!("{:?}", value))
)
.unwrap();
self.comma = true;
} else {
write!(
&mut self.stderr,
Expand All @@ -130,8 +129,8 @@ impl<'a> Visit for Event<'a> {
value
)
.unwrap();
self.comma = true;
}
self.comma = true;
}
}

Expand Down
4 changes: 2 additions & 2 deletions tracing-core/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,10 +832,10 @@ mod tests {
(LevelFilter::TRACE, Some(Level::TRACE)),
];
for (filter, level) in mapping.iter() {
assert_eq!(filter.clone().into_level(), *level);
assert_eq!(filter.into_level(), *level);
match level {
Some(level) => {
let actual: LevelFilter = level.clone().into();
let actual: LevelFilter = (*level).into();
assert_eq!(actual, *filter);
}
None => {
Expand Down
3 changes: 1 addition & 2 deletions tracing-error/src/subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ where
let span = subscriber
.span(id)
.expect("registry should have a span for the current ID");
let parents = span.parents();
for span in std::iter::once(span).chain(parents) {
for span in span.scope() {
let cont = if let Some(fields) = span.extensions().get::<FormattedFields<F>>() {
f(span.metadata(), fields.fields.as_str())
} else {
Expand Down
23 changes: 9 additions & 14 deletions tracing-flame/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,12 +394,10 @@ where

let first = ctx.span(id).expect("expected: span id exists in registry");

if !self.config.empty_samples && first.from_root().count() == 0 {
if !self.config.empty_samples && first.parent().is_none() {
return;
}

let parents = first.from_root();

let mut stack = String::new();

if !self.config.threads_collapsed {
Expand All @@ -408,9 +406,12 @@ where
stack += "all-threads";
}

for parent in parents {
stack += "; ";
write(&mut stack, parent, &self.config).expect("expected: write to String never fails");
if let Some(second) = first.parent() {
for parent in second.scope().from_root() {
stack += "; ";
write(&mut stack, parent, &self.config)
.expect("expected: write to String never fails");
}
}

write!(&mut stack, " {}", samples.as_nanos())
Expand Down Expand Up @@ -440,28 +441,22 @@ where

let samples = self.time_since_last_event();
let first = expect!(ctx.span(&id), "expected: span id exists in registry");
let parents = first.from_root();

let mut stack = String::new();
if !self.config.threads_collapsed {
THREAD_NAME.with(|name| stack += name.as_str());
} else {
stack += "all-threads";
}
stack += "; ";

for parent in parents {
for parent in first.scope().from_root() {
stack += "; ";
expect!(
write(&mut stack, parent, &self.config),
"expected: write to String never fails"
);
stack += "; ";
}

expect!(
write(&mut stack, first, &self.config),
"expected: write to String never fails"
);
expect!(
write!(&mut stack, " {}", samples.as_nanos()),
"expected: write to String never fails"
Expand Down
10 changes: 7 additions & 3 deletions tracing-journald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ where
let span = ctx.span(id).expect("unknown span");
let mut buf = Vec::with_capacity(256);

let depth = span.parents().count();
let depth = span.scope().skip(1).count();

writeln!(buf, "S{}_NAME", depth).unwrap();
put_value(&mut buf, span.name().as_bytes());
Expand All @@ -143,7 +143,7 @@ where

fn on_record(&self, id: &Id, values: &Record, ctx: Context<C>) {
let span = ctx.span(id).expect("unknown span");
let depth = span.parents().count();
let depth = span.scope().skip(1).count();
let mut exts = span.extensions_mut();
let buf = &mut exts.get_mut::<SpanFields>().expect("missing fields").0;
values.record(&mut SpanVisitor {
Expand All @@ -157,7 +157,11 @@ where
let mut buf = Vec::with_capacity(256);

// Record span fields
for span in ctx.scope() {
for span in ctx
.lookup_current()
.into_iter()
.flat_map(|span| span.scope().from_root())
{
let exts = span.extensions();
let fields = exts.get::<SpanFields>().expect("missing fields");
buf.extend_from_slice(&fields.0);
Expand Down
7 changes: 3 additions & 4 deletions tracing-subscriber/src/filter/env/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ impl EnvFilter {
let bold = Style::new().bold();
let mut warning = Color::Yellow.paint("warning");
warning.style_ref_mut().is_bold = true;
format!("{}{} {}", warning, bold.clone().paint(":"), bold.paint(msg))
format!("{}{} {}", warning, bold.paint(":"), bold.paint(msg))
};
eprintln!("{}", msg);
};
Expand Down Expand Up @@ -304,7 +304,6 @@ impl EnvFilter {
};
let level = directive
.level
.clone()
.into_level()
.expect("=off would not have enabled any filters");
ctx(&format!(
Expand Down Expand Up @@ -392,8 +391,8 @@ impl<S: Collect> Subscribe<S> for EnvFilter {
return Some(LevelFilter::TRACE);
}
std::cmp::max(
self.statics.max_level.clone().into(),
self.dynamics.max_level.clone().into(),
self.statics.max_level.into(),
self.dynamics.max_level.into(),
)
}

Expand Down
2 changes: 1 addition & 1 deletion tracing-subscriber/src/filter/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ impl<S: Collect> crate::Subscribe<S> for LevelFilter {
}

fn max_level_hint(&self) -> Option<LevelFilter> {
self.clone().into()
Some(*self)
}
}
15 changes: 11 additions & 4 deletions tracing-subscriber/src/fmt/fmt_subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
field::RecordFields,
fmt::{format, FormatEvent, FormatFields, MakeWriter, TestWriter},
registry::{LookupSpan, SpanRef},
subscribe::{self, Context, Scope},
subscribe::{self, Context},
};
use format::{FmtSpan, TimingDisplay};
use std::{
Expand Down Expand Up @@ -756,8 +756,10 @@ where
F: FnMut(&SpanRef<'_, S>) -> Result<(), E>,
{
// visit all the current spans
for span in self.ctx.scope() {
f(&span)?;
if let Some(leaf) = self.ctx.lookup_current() {
for span in leaf.scope().from_root() {
f(&span)?;
}
}
Ok(())
}
Expand Down Expand Up @@ -816,7 +818,12 @@ where
/// the current span.
///
/// [stored data]: SpanRef
pub fn scope(&self) -> Scope<'_, S>
#[deprecated(
note = "wraps layer::Context::scope, which is deprecated",
since = "0.2.19"
)]
#[allow(deprecated)]
pub fn scope(&self) -> crate::subscribe::Scope<'_, S>
where
S: for<'lookup> LookupSpan<'lookup>,
{
Expand Down
6 changes: 4 additions & 2 deletions tracing-subscriber/src/fmt/format/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,10 @@ where
use serde::ser::SerializeSeq;
let mut serializer = serializer_o.serialize_seq(None)?;

for span in self.0.scope() {
serializer.serialize_element(&SerializableSpan(&span, self.1))?;
if let Some(leaf_span) = self.0.lookup_current() {
for span in leaf_span.scope().from_root() {
serializer.serialize_element(&SerializableSpan(&span, self.1))?;
}
}

serializer.end()
Expand Down
42 changes: 18 additions & 24 deletions tracing-subscriber/src/fmt/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use crate::{

use std::{
fmt::{self, Write},
iter,
marker::PhantomData,
};
use tracing_core::{
Expand Down Expand Up @@ -650,10 +649,7 @@ where
.and_then(|id| ctx.ctx.span(&id))
.or_else(|| ctx.ctx.lookup_current());

let scope = span.into_iter().flat_map(|span| {
let parents = span.parents();
iter::once(span).chain(parents)
});
let scope = span.into_iter().flat_map(|span| span.scope());
#[cfg(feature = "ansi")]
let dimmed = if self.ansi {
Style::new().dimmed()
Expand Down Expand Up @@ -876,9 +872,7 @@ where
.and_then(|id| self.ctx.ctx.span(&id))
.or_else(|| self.ctx.ctx.lookup_current());

let scope = span
.into_iter()
.flat_map(|span| span.from_root().chain(iter::once(span)));
let scope = span.into_iter().flat_map(|span| span.scope().from_root());

for span in scope {
write!(f, "{}", bold.paint(span.metadata().name()))?;
Expand Down Expand Up @@ -1414,27 +1408,27 @@ pub(super) mod test {
#[test]
fn fmt_span_combinations() {
let f = FmtSpan::NONE;
assert_eq!(f.contains(FmtSpan::NEW), false);
assert_eq!(f.contains(FmtSpan::ENTER), false);
assert_eq!(f.contains(FmtSpan::EXIT), false);
assert_eq!(f.contains(FmtSpan::CLOSE), false);
assert!(!f.contains(FmtSpan::NEW));
assert!(!f.contains(FmtSpan::ENTER));
assert!(!f.contains(FmtSpan::EXIT));
assert!(!f.contains(FmtSpan::CLOSE));

let f = FmtSpan::ACTIVE;
assert_eq!(f.contains(FmtSpan::NEW), false);
assert_eq!(f.contains(FmtSpan::ENTER), true);
assert_eq!(f.contains(FmtSpan::EXIT), true);
assert_eq!(f.contains(FmtSpan::CLOSE), false);
assert!(!f.contains(FmtSpan::NEW));
assert!(f.contains(FmtSpan::ENTER));
assert!(f.contains(FmtSpan::EXIT));
assert!(!f.contains(FmtSpan::CLOSE));

let f = FmtSpan::FULL;
assert_eq!(f.contains(FmtSpan::NEW), true);
assert_eq!(f.contains(FmtSpan::ENTER), true);
assert_eq!(f.contains(FmtSpan::EXIT), true);
assert_eq!(f.contains(FmtSpan::CLOSE), true);
assert!(f.contains(FmtSpan::NEW));
assert!(f.contains(FmtSpan::ENTER));
assert!(f.contains(FmtSpan::EXIT));
assert!(f.contains(FmtSpan::CLOSE));

let f = FmtSpan::NEW | FmtSpan::CLOSE;
assert_eq!(f.contains(FmtSpan::NEW), true);
assert_eq!(f.contains(FmtSpan::ENTER), false);
assert_eq!(f.contains(FmtSpan::EXIT), false);
assert_eq!(f.contains(FmtSpan::CLOSE), true);
assert!(f.contains(FmtSpan::NEW));
assert!(!f.contains(FmtSpan::ENTER));
assert!(!f.contains(FmtSpan::EXIT));
assert!(f.contains(FmtSpan::CLOSE));
}
}
10 changes: 2 additions & 8 deletions tracing-subscriber/src/fmt/format/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ use crate::{
registry::LookupSpan,
};

use std::{
fmt::{self, Write},
iter,
};
use std::fmt::{self, Write};
use tracing_core::{
field::{self, Field},
Collect, Event, Level,
Expand Down Expand Up @@ -186,10 +183,7 @@ where
.and_then(|id| ctx.span(&id))
.or_else(|| ctx.lookup_current());

let scope = span.into_iter().flat_map(|span| {
let parents = span.parents();
iter::once(span).chain(parents)
});
let scope = span.into_iter().flat_map(|span| span.scope());

for span in scope {
let meta = span.metadata();
Expand Down
Loading

0 comments on commit 3a5d175

Please sign in to comment.