//! Helpers the integration tests of this crate share. // Each integration test crate of this directory uses some of these helpers. #![allow(dead_code)] use std::fmt::{self, Write as _}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use tracing::field::{Field, Visit}; use tracing::level_filters::LevelFilter; use tracing::span::{Attributes, Id, Record}; use tracing::{Event, Metadata, Subscriber}; /// A subscriber that keeps every event and span it sees as one line of text /// each: level, target and every field with its `Debug` text, as a log line /// would show them. struct Capture { lines: Arc>>, spans: AtomicU64, } impl Capture { fn push(&self, line: String) { self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line); } } /// The fields of an event or a span as ` name=value` text. struct Fields<'a>(&'a mut String); impl Visit for Fields<'_> { fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { let _ = write!(self.0, " {}={value:?}", field.name()); } } impl Subscriber for Capture { fn enabled(&self, _: &Metadata<'_>) -> bool { true } fn max_level_hint(&self) -> Option { Some(LevelFilter::TRACE) } fn new_span(&self, attributes: &Attributes<'_>) -> Id { let mut line = format!("span {}", attributes.metadata().name()); attributes.record(&mut Fields(&mut line)); self.push(line); Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1) } fn record(&self, _: &Id, values: &Record<'_>) { let mut line = String::from("span record"); values.record(&mut Fields(&mut line)); self.push(line); } fn record_follows_from(&self, _: &Id, _: &Id) {} fn event(&self, event: &Event<'_>) { let metadata = event.metadata(); let mut line = format!("{} {}:", metadata.level(), metadata.target()); event.record(&mut Fields(&mut line)); self.push(line); } fn enter(&self, _: &Id) {} fn exit(&self, _: &Id) {} } /// Run `f` on this thread with a subscriber that takes in everything logged at /// TRACE and above, and return what `f` returned with the lines logged. pub fn at_trace(f: impl FnOnce() -> R) -> (R, Vec) { let lines = Arc::new(Mutex::new(Vec::new())); let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) }; let out = tracing::subscriber::with_default(subscriber, f); let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner)); (out, lines) } /// How many of the lines say that a checkpoint was blocked. pub fn blocked_checkpoints(lines: &[String]) -> usize { lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count() }