use std::{
io,
sync::{Arc, Mutex, OnceLock},
};
use tracing_subscriber::fmt::format::FmtSpan;
use super::terminator_tests::{
BeforeSendProbe,
CompletionProbe,
TaggedFrame,
forward_finished_stream,
forward_finished_stream_with,
};
fn keep_interest_cache_permissive() {
static REGISTRIES: OnceLock<Vec<tracing::Dispatch>> = OnceLock::new();
let kept = REGISTRIES.get_or_init(|| {
(0..2)
.map(|_| tracing::Dispatch::new(tracing_subscriber::registry()))
.collect()
});
debug_assert_eq!(
kept.len(),
2,
"both permissive registries must stay registered"
);
}
#[derive(Clone, Default)]
struct CapturedOutput(Arc<Mutex<Vec<u8>>>);
impl CapturedOutput {
fn text(&self) -> String {
self.0
.lock()
.map(|buffer| String::from_utf8_lossy(&buffer).into_owned())
.unwrap_or_default()
}
}
impl io::Write for CapturedOutput {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let mut buffer = self
.0
.lock()
.map_err(|error| io::Error::other(error.to_string()))?;
buffer.extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedOutput {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer { self.clone() }
}
fn capture_spans(captured: &CapturedOutput) -> tracing::subscriber::DefaultGuard {
keep_interest_cache_permissive();
let subscriber = tracing_subscriber::fmt()
.with_writer(captured.clone())
.with_ansi(false)
.with_max_level(tracing::Level::TRACE)
.with_span_events(FmtSpan::CLOSE)
.finish();
let guard = tracing::subscriber::set_default(subscriber);
tracing::callsite::rebuild_interest_cache();
guard
}
#[tokio::test]
async fn a_completed_stream_records_its_outcome_on_the_delivery_span() {
let captured = CapturedOutput::default();
let _capture = capture_spans(&captured);
let frames = forward_finished_stream()
.await
.expect("the finished stream must be forwarded");
assert_eq!(
frames.len(),
1,
"the finished stream writes its protocol terminator"
);
let output = captured.text();
assert!(
output.contains("response_delivery"),
"the delivery span must reach the subscriber; captured: {output}"
);
for field in [
"request_id=7",
"correlation_id=Some(3)",
"streaming=true",
"outcome=Completed",
] {
assert!(
output.contains(field),
"the delivery span must report {field}; captured: {output}"
);
}
}
const NO_SPAN: &str = "<no span>";
fn current_span_name() -> &'static str {
tracing::Span::current()
.metadata()
.map_or(NO_SPAN, |metadata| metadata.name())
}
#[derive(Clone, Default)]
struct SpanObservations(Arc<Mutex<SpanRecords>>);
#[derive(Clone, Default)]
struct SpanRecords {
before_send: Vec<&'static str>,
command_end: Vec<&'static str>,
}
impl SpanObservations {
fn record_before_send(&self, span: &'static str) { self.lock().before_send.push(span); }
fn record_command_end(&self, span: &'static str) { self.lock().command_end.push(span); }
fn records(&self) -> SpanRecords { self.lock().clone() }
fn lock(&self) -> std::sync::MutexGuard<'_, SpanRecords> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
fn span_probing_before_send(observations: SpanObservations) -> BeforeSendProbe {
Arc::new(move |_frame: &mut TaggedFrame| {
observations.record_before_send(current_span_name());
})
}
fn span_probing_completion(observations: SpanObservations) -> CompletionProbe {
Arc::new(move || observations.record_command_end(current_span_name()))
}
#[tokio::test]
async fn the_delivery_span_covers_the_terminator_and_completion_hook() {
let _capture = capture_spans(&CapturedOutput::default());
let observations = SpanObservations::default();
let frames = forward_finished_stream_with(
Some(span_probing_completion(observations.clone())),
Some(span_probing_before_send(observations.clone())),
)
.await
.expect("the finished stream must be forwarded");
assert_eq!(
frames.len(),
1,
"the finished stream writes its protocol terminator"
);
let records = observations.records();
assert_eq!(
records.before_send,
vec!["response_delivery"],
"the terminator's before_send hook must run inside the delivery span"
);
assert_eq!(
records.command_end,
vec!["response_delivery"],
"the completion hook must run inside the delivery span"
);
}