use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{ready, Context as TaskContext, Poll};
use opentelemetry::trace::{SpanKind, Status, TraceContextExt};
use opentelemetry::{Context, KeyValue};
use opentelemetry_sdk::trace::SdkTracer;
use pin_project_lite::pin_project;
use super::{extract_headers, helpers::mark_error_on, start_span, SpanOptions};
pub type SpanNamer = fn(&http::Method, &http::Uri) -> String;
fn default_name(method: &http::Method, _uri: &http::Uri) -> String {
method.as_str().to_string()
}
#[derive(Clone)]
pub struct TraceLayer {
tracer: Option<SdkTracer>,
namer: SpanNamer,
}
impl fmt::Debug for TraceLayer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TraceLayer").finish_non_exhaustive()
}
}
impl Default for TraceLayer {
fn default() -> Self {
TraceLayer {
tracer: None,
namer: default_name,
}
}
}
impl TraceLayer {
pub fn new() -> Self {
Self::default()
}
pub fn with_tracer(mut self, tracer: SdkTracer) -> Self {
self.tracer = Some(tracer);
self
}
pub fn with_span_namer(mut self, namer: SpanNamer) -> Self {
self.namer = namer;
self
}
}
impl<S> tower::Layer<S> for TraceLayer {
type Service = TraceService<S>;
fn layer(&self, inner: S) -> TraceService<S> {
TraceService {
inner,
layer: self.clone(),
}
}
}
#[derive(Clone)]
pub struct TraceService<S> {
inner: S,
layer: TraceLayer,
}
impl<S> fmt::Debug for TraceService<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TraceService").finish_non_exhaustive()
}
}
impl<S, ReqB, ResB> tower::Service<http::Request<ReqB>> for TraceService<S>
where
S: tower::Service<http::Request<ReqB>, Response = http::Response<ResB>>,
S::Error: fmt::Display,
{
type Response = S::Response;
type Error = S::Error;
type Future = TraceFuture<S::Future>;
fn poll_ready(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: http::Request<ReqB>) -> Self::Future {
let uri = req.uri();
let mut opts = SpanOptions::default()
.kind(SpanKind::Server)
.parent(extract_headers(req.headers()))
.attribute(KeyValue::new(
"http.request.method",
req.method().as_str().to_string(),
))
.attribute(KeyValue::new("url.path", uri.path().to_string()));
if let Some(scheme) = uri.scheme_str() {
opts = opts.attribute(KeyValue::new("url.scheme", scheme.to_string()));
}
let host = uri.host().map(str::to_string).or_else(|| {
req.headers()
.get(http::header::HOST)
.and_then(|h| h.to_str().ok())
.map(|h| h.split(':').next().unwrap_or(h).to_string())
});
if let Some(host) = host {
opts = opts.attribute(KeyValue::new("server.address", host));
}
if let Some(ua) = req
.headers()
.get(http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
{
opts = opts.attribute(KeyValue::new("user_agent.original", ua.to_string()));
}
if let Some(tracer) = &self.layer.tracer {
opts = opts.tracer(tracer.clone());
}
let cx = start_span((self.layer.namer)(req.method(), uri), opts);
let inner = {
let _guard = cx.clone().attach();
self.inner.call(req)
};
TraceFuture {
inner,
cx: Some(cx),
}
}
}
pin_project! {
pub struct TraceFuture<F> {
#[pin]
inner: F,
cx: Option<Context>,
}
}
impl<F> fmt::Debug for TraceFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TraceFuture").finish_non_exhaustive()
}
}
impl<F, ResB, E> Future for TraceFuture<F>
where
F: Future<Output = Result<http::Response<ResB>, E>>,
E: fmt::Display,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, task: &mut TaskContext<'_>) -> Poll<Self::Output> {
let this = self.project();
let result = {
let _guard = this.cx.as_ref().map(|c| c.clone().attach());
ready!(this.inner.poll(task))
};
if let Some(cx) = this.cx.take() {
let span = cx.span();
match &result {
Ok(resp) => {
let code = resp.status().as_u16();
span.set_attribute(KeyValue::new("http.response.status_code", i64::from(code)));
if code >= 500 {
span.set_status(Status::error(format!("HTTP {code}")));
}
}
Err(e) => mark_error_on(&span, std::any::type_name::<E>(), e),
}
span.end();
}
Poll::Ready(result)
}
}