2022-06-30 06:54:54 -07:00
|
|
|
use reqwest::{Request, Response};
|
|
|
|
use reqwest_middleware::{Middleware, Next, Result};
|
2021-09-28 11:50:23 -07:00
|
|
|
use task_local_extensions::Extensions;
|
2022-04-21 10:39:06 -07:00
|
|
|
use tracing::Instrument;
|
2021-08-10 09:07:08 -07:00
|
|
|
|
2022-06-30 06:54:54 -07:00
|
|
|
use crate::{DefaultSpanBackend, ReqwestOtelSpanBackend};
|
|
|
|
|
2021-08-10 09:07:08 -07:00
|
|
|
/// Middleware for tracing requests using the current Opentelemetry Context.
|
2022-06-30 06:54:54 -07:00
|
|
|
pub struct TracingMiddleware<S: ReqwestOtelSpanBackend> {
|
|
|
|
span_backend: std::marker::PhantomData<S>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S: ReqwestOtelSpanBackend> TracingMiddleware<S> {
|
|
|
|
pub fn new() -> TracingMiddleware<S> {
|
|
|
|
TracingMiddleware {
|
|
|
|
span_backend: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for TracingMiddleware<DefaultSpanBackend> {
|
|
|
|
fn default() -> Self {
|
|
|
|
TracingMiddleware::new()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S: ReqwestOtelSpanBackend> Clone for TracingMiddleware<S> {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
Self::new()
|
|
|
|
}
|
|
|
|
}
|
2021-08-10 09:07:08 -07:00
|
|
|
|
|
|
|
#[async_trait::async_trait]
|
2022-06-30 06:54:54 -07:00
|
|
|
impl<ReqwestOtelSpan> Middleware for TracingMiddleware<ReqwestOtelSpan>
|
|
|
|
where
|
|
|
|
ReqwestOtelSpan: ReqwestOtelSpanBackend + Sync + Send + 'static,
|
|
|
|
{
|
2021-08-10 09:07:08 -07:00
|
|
|
async fn handle(
|
|
|
|
&self,
|
|
|
|
req: Request,
|
|
|
|
extensions: &mut Extensions,
|
|
|
|
next: Next<'_>,
|
|
|
|
) -> Result<Response> {
|
2022-06-30 06:54:54 -07:00
|
|
|
let request_span = ReqwestOtelSpan::on_request_start(&req, extensions);
|
2021-08-10 09:07:08 -07:00
|
|
|
|
2022-06-30 06:54:54 -07:00
|
|
|
let outcome_future = async {
|
2022-04-21 10:39:06 -07:00
|
|
|
// Adds tracing headers to the given request to propagate the OpenTelemetry context to downstream revivers of the request.
|
|
|
|
// Spans added by downstream consumers will be part of the same trace.
|
|
|
|
#[cfg(any(
|
|
|
|
feature = "opentelemetry_0_13",
|
|
|
|
feature = "opentelemetry_0_14",
|
|
|
|
feature = "opentelemetry_0_15",
|
|
|
|
feature = "opentelemetry_0_16",
|
|
|
|
feature = "opentelemetry_0_17",
|
|
|
|
))]
|
|
|
|
let req = crate::otel::inject_opentelemetry_context_into_request(req);
|
2021-08-10 09:07:08 -07:00
|
|
|
|
2022-04-21 10:39:06 -07:00
|
|
|
// Run the request
|
|
|
|
let outcome = next.run(req, extensions).await;
|
2022-06-30 06:54:54 -07:00
|
|
|
ReqwestOtelSpan::on_request_end(&request_span, &outcome, extensions);
|
2022-04-21 10:39:06 -07:00
|
|
|
outcome
|
2022-06-30 06:54:54 -07:00
|
|
|
};
|
2021-08-10 09:07:08 -07:00
|
|
|
|
2022-06-30 06:54:54 -07:00
|
|
|
outcome_future.instrument(request_span.clone()).await
|
2021-08-10 09:07:08 -07:00
|
|
|
}
|
|
|
|
}
|