Skip to main content

oxtel_reqwest/
lib.rs

1//! HTTP client spans and metrics for [reqwest](https://docs.rs/reqwest),
2//! as the OpenTelemetry semantic conventions describe, with the trace
3//! carried on to the server. Part of
4//! [oxtel](https://github.com/agentstatelabs/oxtel).
5//!
6//! One line wraps a reqwest client, and requests are made as before:
7//!
8//! ```no_run
9//! # async fn run() -> Result<(), reqwest_middleware::Error> {
10//! let client = oxtel_reqwest::client(reqwest::Client::new());
11//! let items = client.get("https://api.example/items").send().await?.text().await?;
12//! # Ok(()) }
13//! ```
14//!
15//! Every request gets:
16//!
17//! - **a client span** named for its method, with `http.request.method`,
18//!   `server.address`, `server.port`, `url.full`,
19//!   `network.protocol.version` and `http.response.status_code`. A 4xx or
20//!   5xx response, or a request that got no response, is an error, with
21//!   `error.type` saying why: the status code, or `timeout`, `connect`,
22//!   `redirect`, `body`, `decode` or `request`.
23//! - **W3C `traceparent` and `tracestate` headers**, so a server that
24//!   reads them, such as one with oxtel-tower's `HttpServerLayer`,
25//!   continues the trace.
26//! - **`http.client.request.duration`** in seconds, by method, server,
27//!   scheme, status and `error.type`.
28//!
29//! The query string and any credentials in the URL are never recorded,
30//! since either may hold secrets. These are the spans and metrics
31//! oxtel-tower's `HttpClientLayer` records, so a program using both gets
32//! the same telemetry from each.
33//!
34//! [`client`] returns reqwest-middleware's
35//! [`ClientWithMiddleware`],
36//! whose methods are reqwest's own. A program with other middleware adds
37//! [`HttpClientMiddleware`] with the rest. After retry middleware, each
38//! attempt gets a span of its own; a redirect that reqwest follows itself is
39//! part of the same span.
40//!
41//! ```
42//! let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
43//!     // No trace context for requests that leave your systems.
44//!     .with(oxtel_reqwest::HttpClientMiddleware::new().with_propagation(false))
45//!     .build();
46//! ```
47//!
48//! Spans are recorded with `tracing` and metrics with `metrics`, so they go
49//! wherever the program's subscriber and recorder send them: with
50//! `oxtel::init()`, to OTLP or Prometheus. Make the client after
51//! `oxtel::init()`, so the duration is recorded in seconds with the
52//! conventions' buckets.
53
54use http::Extensions;
55use oxtel_tower::{ClientCall, ClientRequestInfo};
56use reqwest::{Request, Response};
57use reqwest_middleware::{ClientWithMiddleware, Middleware, Next};
58use tracing::Instrument;
59
60pub use reqwest_middleware;
61
62/// `client`, with every request it makes recorded: [`HttpClientMiddleware`]
63/// with its defaults.
64pub fn client(client: reqwest::Client) -> ClientWithMiddleware {
65    reqwest_middleware::ClientBuilder::new(client)
66        .with(HttpClientMiddleware::new())
67        .build()
68}
69
70/// reqwest-middleware middleware that records each request: a client span,
71/// trace context sent along, and `http.client.request.duration`. See the
72/// [crate documentation](crate).
73#[derive(Clone, Debug)]
74pub struct HttpClientMiddleware {
75    propagate: bool,
76    metrics: bool,
77}
78
79impl Default for HttpClientMiddleware {
80    fn default() -> Self {
81        HttpClientMiddleware::new()
82    }
83}
84
85impl HttpClientMiddleware {
86    /// Spans, propagation and metrics on.
87    pub fn new() -> Self {
88        oxtel_tower::describe_metrics();
89        HttpClientMiddleware {
90            propagate: true,
91            metrics: true,
92        }
93    }
94
95    /// Send W3C trace context with each request. Default: true. Turn it off
96    /// for requests leaving your trust boundary.
97    pub fn with_propagation(mut self, enabled: bool) -> Self {
98        self.propagate = enabled;
99        self
100    }
101
102    /// Record `http.client.request.duration`. Default: true.
103    pub fn with_metrics(mut self, enabled: bool) -> Self {
104        self.metrics = enabled;
105        self
106    }
107}
108
109#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
110#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
111impl Middleware for HttpClientMiddleware {
112    async fn handle(
113        &self,
114        mut req: Request,
115        extensions: &mut Extensions,
116        next: Next<'_>,
117    ) -> reqwest_middleware::Result<Response> {
118        let url = req.url();
119        let mut call = ClientCall::start(&ClientRequestInfo {
120            method: req.method(),
121            scheme: url.scheme(),
122            // An IPv6 address without its brackets, as the conventions
123            // record it.
124            server_address: url
125                .host_str()
126                .map(|host| host.trim_start_matches('[').trim_end_matches(']')),
127            server_port: url.port_or_known_default(),
128            path: url.path(),
129            protocol_version: req.version(),
130        });
131        if !self.metrics {
132            call = call.without_metrics();
133        }
134        if self.propagate {
135            call.inject_trace_context(req.headers_mut());
136        }
137        let span = call.span().clone();
138        let result = next.run(req, extensions).instrument(span).await;
139        match &result {
140            Ok(response) => call.finish(response.status(), response.version()),
141            Err(error) => call.fail(error_type(error)),
142        }
143        result
144    }
145}
146
147/// `error.type` for a request that got no response: a short name for what
148/// went wrong, few enough to be a metric label.
149fn error_type(error: &reqwest_middleware::Error) -> &'static str {
150    let error = match error {
151        reqwest_middleware::Error::Reqwest(error) => error,
152        reqwest_middleware::Error::Middleware(_) => return "middleware",
153    };
154    if error.is_timeout() {
155        "timeout"
156    } else if error.is_connect() {
157        "connect"
158    } else if error.is_redirect() {
159        "redirect"
160    } else if error.is_body() {
161        "body"
162    } else if error.is_decode() {
163        "decode"
164    } else if error.is_builder() {
165        "builder"
166    } else if error.is_request() {
167        "request"
168    } else {
169        "reqwest::Error"
170    }
171}