use axum::http::HeaderMap;
use redup_bootstrap_grpc::TraceIds;
use uuid::Uuid;
#[cfg(not(feature = "otlp"))]
use crate::telemetry::traceparent::hex;
use crate::telemetry::traceparent::{HEADER, SpanId, TraceId, TraceParent, parse};
pub(crate) const CORRELATION_HEADER: &str = "x-correlation-id";
pub(crate) struct Opened {
pub(crate) span: tracing::Span,
pub(crate) trace: TraceIds,
}
pub(crate) fn open(headers: &HeaderMap, route: &str, method: &str) -> Opened {
open_with(headers, route, method, random_trace_id(), random_span_id())
}
pub(crate) fn open_with(
headers: &HeaderMap,
route: &str,
method: &str,
new_trace: TraceId,
new_span: SpanId,
) -> Opened {
let correlation_id = headers
.get(CORRELATION_HEADER)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.map_or_else(|| Uuid::new_v4().to_string(), str::to_owned);
let parent: Option<TraceParent> = headers
.get(HEADER)
.and_then(|value| value.to_str().ok())
.and_then(parse);
#[cfg(not(feature = "otlp"))]
{
let trace_id = parent.map_or(new_trace, |parent| parent.trace_id);
let span = local(route, method, &correlation_id, trace_id, new_span);
Opened {
span,
trace: TraceIds {
trace: trace_id,
span: new_span,
sampled: parent.is_none_or(|parent| parent.sampled),
},
}
}
#[cfg(feature = "otlp")]
{
crate::telemetry::otlp::open(
headers,
route,
method,
parent,
&correlation_id,
(new_trace, new_span),
)
}
}
#[cfg(not(feature = "otlp"))]
fn local(
route: &str,
method: &str,
correlation_id: &str,
trace_id: TraceId,
span_id: SpanId,
) -> tracing::Span {
tracing::info_span!(
"request",
http.route = route,
http.method = method,
http.status_code = tracing::field::Empty,
correlation_id = correlation_id,
trace_id = hex(&trace_id).as_str(),
span_id = hex(&span_id).as_str(),
)
}
fn random_trace_id() -> TraceId {
*Uuid::new_v4().as_bytes()
}
fn random_span_id() -> SpanId {
let uuid = Uuid::new_v4();
let bytes = uuid.as_bytes();
[
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]
}
#[cfg(test)]
mod tests {
use axum::http::HeaderMap;
use serde_json::Value;
use tracing_subscriber::layer::SubscriberExt;
use super::{CORRELATION_HEADER, open_with};
use crate::telemetry::journal::{Journal, Output};
use crate::telemetry::logs_config::LogsConfig;
use crate::telemetry::service::Service;
use crate::telemetry::template::Template;
use crate::telemetry::{Level, traceparent::HEADER};
const TRACE: [u8; 16] = [0x11; 16];
const SPAN: [u8; 8] = [0x22; 8];
fn line_of(headers: HeaderMap, status: u16) -> String {
let buffer = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let config = LogsConfig::with(Level::Trace, Template::Json);
let journal = Journal::new(
config,
Service::new("trial", "1.0.0"),
Output::Buffer(std::sync::Arc::clone(&buffer)),
crate::telemetry::journal::system_clock(),
);
let subscriber = tracing_subscriber::registry().with(journal);
let _default = tracing::subscriber::set_default(subscriber);
let opened = open_with(&headers, "/readyz/{name}", "GET", TRACE, SPAN);
let _entered = opened.span.enter();
tracing::info!("handled");
opened.span.record("http.status_code", status);
drop(_entered);
drop(_default);
let text = String::from_utf8(buffer.lock().expect("the buffer").clone()).expect("UTF-8");
text.trim_end().to_owned()
}
fn property<'a>(line: &'a Value, name: &str) -> &'a Value {
&line["EventProperties"][name]
}
#[test]
fn correlation_and_trace_are_taken_from_the_headers() {
let mut headers = HeaderMap::new();
headers.insert(
CORRELATION_HEADER,
"6f107bf6-289b-4421-acee-40e1b9f5b4c9"
.parse()
.expect("a header value"),
);
headers.insert(
HEADER,
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
.parse()
.expect("a header value"),
);
let line: Value = serde_json::from_str(&line_of(headers, 200)).expect("a JSON line");
assert_eq!(
line["CorrelationId"],
"6f107bf6-289b-4421-acee-40e1b9f5b4c9"
);
assert_eq!(
property(&line, "traceId"),
"4bf92f3577b34da6a3ce929d0e0e4736"
);
assert_eq!(property(&line, "spanId"), "2222222222222222");
}
#[test]
fn without_headers_a_new_trace_and_correlation_start() {
let line: Value =
serde_json::from_str(&line_of(HeaderMap::new(), 200)).expect("a JSON line");
let correlation = line["CorrelationId"].as_str().expect("a correlation id");
assert!(uuid::Uuid::parse_str(correlation).is_ok());
assert_eq!(
property(&line, "traceId"),
"11111111111111111111111111111111"
);
assert_eq!(property(&line, "spanId"), "2222222222222222");
}
#[test]
fn broken_trace_parent_starts_a_new_trace() {
let mut headers = HeaderMap::new();
headers.insert(HEADER, "00-broken".parse().expect("a header value"));
let line: Value = serde_json::from_str(&line_of(headers, 200)).expect("a JSON line");
assert_eq!(
property(&line, "traceId"),
"11111111111111111111111111111111"
);
}
#[test]
fn blank_correlation_is_replaced() {
let mut headers = HeaderMap::new();
headers.insert(CORRELATION_HEADER, " ".parse().expect("a header value"));
let line: Value = serde_json::from_str(&line_of(headers, 200)).expect("a JSON line");
assert_ne!(line["CorrelationId"], "");
}
}