use core::fmt;
use std::mem;
use tracing::field::{Field, Visit};
use super::CORRELATION_FIELD;
use super::SPAN_FIELD;
use super::TRACE_FIELD;
#[derive(Debug, Clone, Default)]
pub(crate) struct SpanContext {
correlation_id: Option<String>,
trace_id: Option<String>,
span_id: Option<String>,
}
impl SpanContext {
pub(crate) fn from_attributes(attributes: &tracing::span::Attributes<'_>) -> Self {
let mut reader = Reader(Self::default());
attributes.record(&mut reader);
reader.0
}
pub(crate) fn from_record(record: &tracing::span::Record<'_>) -> Self {
let mut context = Self::default();
context.amend(record);
context
}
pub(crate) fn amend(&mut self, record: &tracing::span::Record<'_>) {
let mut reader = Reader(mem::take(self));
record.record(&mut reader);
*self = reader.0;
}
pub(crate) fn merge_missing(&mut self, other: &Self) {
if self.correlation_id.is_none() {
self.correlation_id = other.correlation_id.clone();
}
if self.trace_id.is_none() {
self.trace_id = other.trace_id.clone();
}
if self.span_id.is_none() {
self.span_id = other.span_id.clone();
}
}
pub(crate) fn into_parts(self) -> (Option<String>, Option<String>, Option<String>) {
(self.correlation_id, self.trace_id, self.span_id)
}
}
struct Reader(SpanContext);
impl Reader {
fn take(&mut self, field: &Field, value: Option<String>) {
let value = value.filter(|text| !text.is_empty());
match field.name() {
CORRELATION_FIELD if self.0.correlation_id.is_none() => self.0.correlation_id = value,
TRACE_FIELD if self.0.trace_id.is_none() => self.0.trace_id = value,
SPAN_FIELD if self.0.span_id.is_none() => self.0.span_id = value,
_ => {}
}
}
}
impl Visit for Reader {
fn record_str(&mut self, field: &Field, value: &str) {
self.take(field, Some(value.to_owned()));
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.take(field, Some(format!("{value:?}")));
}
}