Files
pruefwerk/compliance-agent/src/api/trace.rs
T
Sharang ParnerkarandClaude Opus 5.5 8249404a85
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Failing after 14m7s
feat(telemetry): W3C propagation, route-named spans, trace-linked logs
- W3C propagator in init_telemetry; calls to the registry carry
  traceparent, so the registry's spans join Prüfwerk's trace.
- The agent's HTTP server opens one INFO span per request, named after
  the route template and continuing an incoming traceparent (portal,
  registry). The default TraceLayer span was DEBUG (dropped by the INFO
  filter) and recorded the full URI. No path, query or client address.
- opentelemetry-appender-tracing experimental_use_tracing_span_context:
  OTLP log records carry trace_id/span_id, so SigNoz links logs and traces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
2026-10-29 10:04:57 +01:00

147 lines
5.1 KiB
Rust

//! One server span per HTTP request, for `TraceLayer` (instrumentation plan,
//! research/observability/2026-10-28-instrumentation-portal-registry-db.md).
//!
//! The default `TraceLayer` span is DEBUG (so the INFO filter drops it) and
//! records the full URI. This one is INFO, named after the route template
//! (`GET /api/v1/targets/{id}`), continues an incoming `traceparent` (portal,
//! registry) and records no path, query or client address.
use std::time::Duration;
use axum::extract::{MatchedPath, Request};
use axum::response::Response;
use tracing::Span;
/// The health route is polled every few seconds and gets no span.
const UNTRACED: &[&str] = &["/api/v1/health"];
pub fn make_span(req: &Request) -> Span {
let route = req
.extensions()
.get::<MatchedPath>()
.map(MatchedPath::as_str);
if route.is_some_and(|r| UNTRACED.contains(&r)) {
return Span::none();
}
let method = req.method().as_str();
let span = tracing::info_span!(
"http",
otel.name = %format!("{method} {}", route.unwrap_or("unmatched")),
otel.kind = "server",
otel.status_code = tracing::field::Empty,
http.request.method = %method,
http.route = route.unwrap_or(""),
http.response.status_code = tracing::field::Empty,
);
let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok());
compliance_core::telemetry::continue_trace(&span, header("traceparent"), header("tracestate"));
span
}
pub fn on_response(res: &Response, _latency: Duration, span: &Span) {
span.record("http.response.status_code", res.status().as_u16());
if res.status().is_server_error() {
span.record("otel.status_code", "ERROR");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use axum::body::Body;
use axum::routing::get;
use axum::Router;
use std::sync::{Arc, Mutex};
use tower::ServiceExt as _;
use tower_http::trace::TraceLayer;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing_subscriber::layer::{Context, SubscriberExt as _};
use tracing_subscriber::Layer;
/// Every field recorded on any span, as "name=value".
#[derive(Clone, Default)]
struct Fields(Arc<Mutex<Vec<String>>>);
struct Collect<'a>(&'a Mutex<Vec<String>>);
impl Visit for Collect<'_> {
fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) {
self.0.lock().unwrap().push(format!("{}={v:?}", f.name()));
}
fn record_str(&mut self, f: &Field, v: &str) {
self.0.lock().unwrap().push(format!("{}={v}", f.name()));
}
}
impl<S: tracing::Subscriber> Layer<S> for Fields {
fn on_new_span(&self, a: &Attributes<'_>, _: &Id, _: Context<'_, S>) {
a.record(&mut Collect(&self.0));
}
fn on_record(&self, _: &Id, r: &Record<'_>, _: Context<'_, S>) {
r.record(&mut Collect(&self.0));
}
}
async fn call(path: &str, status: u16) -> Vec<String> {
let fields = Fields::default();
let sub = tracing_subscriber::registry().with(fields.clone());
let _guard = tracing::subscriber::set_default(sub);
let app = Router::new()
.route("/api/v1/health", get(|| async { "ok" }))
.route(
"/api/v1/targets/{id}",
get(move || async move { axum::http::StatusCode::from_u16(status).unwrap() }),
)
.layer(
TraceLayer::new_for_http()
.make_span_with(make_span)
.on_response(on_response),
);
let req = Request::builder().uri(path).body(Body::empty()).unwrap();
app.oneshot(req).await.unwrap();
let out = fields.0.lock().unwrap().clone();
out
}
#[tokio::test]
async fn names_the_span_after_the_route_and_keeps_the_path_out() {
let f = call("/api/v1/targets/acme-firmware?token=x", 200).await;
assert!(
f.contains(&"otel.name=GET /api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.route=/api/v1/targets/{id}".to_string()),
"{f:?}"
);
assert!(
f.contains(&"http.response.status_code=200".to_string()),
"{f:?}"
);
assert!(
f.iter()
.all(|x| !x.contains("acme") && !x.contains("token")),
"{f:?}"
);
assert!(
!f.iter().any(|x| x.starts_with("otel.status_code")),
"{f:?}"
);
}
#[tokio::test]
async fn a_server_error_marks_the_span() {
let f = call("/api/v1/targets/1", 503).await;
assert!(f.contains(&"otel.status_code=ERROR".to_string()), "{f:?}");
}
#[tokio::test]
async fn health_and_unmatched() {
assert!(
call("/api/v1/health", 200).await.is_empty(),
"health gets no span"
);
let f = call("/nope/acme", 200).await;
assert!(f.contains(&"otel.name=GET unmatched".to_string()), "{f:?}");
}
}