Skip to main content

oxtel_tower/
client.rs

1//! The HTTP client layer, and [`ClientCall`] for clients that aren't tower
2//! services.
3
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll, ready};
8use std::time::Instant;
9
10use http::{HeaderMap, Method, Request, Response, StatusCode, Version};
11use metrics::Label;
12use oxtel_sdk::propagation::inject_trace_context;
13use oxtel_sdk::trace::{current_span_context, span_context};
14use tower_layer::Layer;
15use tower_service::Service;
16use tracing::Span;
17
18use crate::request::{method_name, protocol_version, server_address};
19
20#[derive(Clone)]
21struct Config {
22    propagate: bool,
23    metrics: bool,
24}
25
26/// Instruments an HTTP client, as the OpenTelemetry semantic conventions
27/// for HTTP clients describe:
28///
29/// - **A span per request**, named for the method, with
30///   `http.request.method`, `server.address`, `server.port`, `url.full`
31///   (without credentials or query), `network.protocol.version`,
32///   `http.response.status_code`, and `error.type` with status Error for
33///   4xx and 5xx responses and failed requests.
34/// - **W3C `traceparent` and `tracestate`** on each request, so the server
35///   continues the trace.
36/// - **`http.client.request.duration`** (seconds) through the `metrics`
37///   facade, by method, server address and port, scheme, status and
38///   `error.type`.
39///
40/// For a client that isn't a tower service, [`ClientCall`] records the
41/// same.
42#[derive(Clone)]
43pub struct HttpClientLayer {
44    config: Arc<Config>,
45}
46
47impl Default for HttpClientLayer {
48    fn default() -> Self {
49        HttpClientLayer::new()
50    }
51}
52
53impl HttpClientLayer {
54    /// A layer with spans, propagation and metrics on.
55    pub fn new() -> Self {
56        crate::describe_metrics();
57        HttpClientLayer {
58            config: Arc::new(Config {
59                propagate: true,
60                metrics: true,
61            }),
62        }
63    }
64
65    /// Send W3C trace context with each request. Default: true. Turn it off
66    /// for requests leaving your trust boundary.
67    pub fn with_propagation(mut self, enabled: bool) -> Self {
68        Arc::make_mut(&mut self.config).propagate = enabled;
69        self
70    }
71
72    /// Record `http.client.request.duration`. Default: true.
73    pub fn with_metrics(mut self, enabled: bool) -> Self {
74        Arc::make_mut(&mut self.config).metrics = enabled;
75        self
76    }
77}
78
79impl<S> Layer<S> for HttpClientLayer {
80    type Service = HttpClient<S>;
81
82    fn layer(&self, inner: S) -> Self::Service {
83        HttpClient {
84            inner,
85            config: Arc::clone(&self.config),
86        }
87    }
88}
89
90/// The service [`HttpClientLayer`] wraps around a client.
91#[derive(Clone)]
92pub struct HttpClient<S> {
93    inner: S,
94    config: Arc<Config>,
95}
96
97impl<S, B, RB> Service<Request<B>> for HttpClient<S>
98where
99    S: Service<Request<B>, Response = Response<RB>>,
100{
101    type Response = Response<RB>;
102    type Error = S::Error;
103    type Future = ResponseFuture<S::Future>;
104
105    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
106        self.inner.poll_ready(cx)
107    }
108
109    fn call(&mut self, mut req: Request<B>) -> Self::Future {
110        let (server_address, server_port) = server_address(&req);
111        let mut call = ClientCall::start(&ClientRequestInfo {
112            method: req.method(),
113            scheme: req.uri().scheme_str().unwrap_or("http"),
114            server_address,
115            server_port,
116            path: req.uri().path(),
117            protocol_version: req.version(),
118        });
119        if !self.config.metrics {
120            call = call.without_metrics();
121        }
122        if self.config.propagate {
123            call.inject_trace_context(req.headers_mut());
124        }
125        let inner = call.span().in_scope(|| self.inner.call(req));
126        ResponseFuture {
127            inner,
128            call: Some(call),
129        }
130    }
131}
132
133pin_project_lite::pin_project! {
134    /// The response future of [`HttpClient`].
135    pub struct ResponseFuture<F> {
136        #[pin]
137        inner: F,
138        call: Option<ClientCall>,
139    }
140}
141
142impl<F, RB, E> Future for ResponseFuture<F>
143where
144    F: Future<Output = Result<Response<RB>, E>>,
145{
146    type Output = Result<Response<RB>, E>;
147
148    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
149        let this = self.project();
150        let _entered = this.call.as_ref().map(|call| call.span().enter());
151        let result = ready!(this.inner.poll(cx));
152        drop(_entered);
153        if let Some(call) = this.call.take() {
154            match &result {
155                Ok(response) => call.finish(response.status(), response.version()),
156                Err(_) => call.fail(std::any::type_name::<E>()),
157            }
158        }
159        Poll::Ready(result)
160    }
161}
162
163/// An outgoing request, as [`ClientCall::start`] records it.
164#[derive(Debug, Clone, Copy)]
165pub struct ClientRequestInfo<'a> {
166    /// The method. Methods outside the standard ones are recorded as
167    /// `_OTHER`, with the method as sent in `http.request.method_original`.
168    pub method: &'a Method,
169    /// `url.scheme`, such as `https`.
170    pub scheme: &'a str,
171    /// `server.address`: the host the request is sent to.
172    pub server_address: Option<&'a str>,
173    /// `server.port`. Without one, the scheme's default port is recorded
174    /// for `http` and `https`.
175    pub server_port: Option<u16>,
176    /// The URL's path. The query isn't taken: it may hold secrets.
177    pub path: &'a str,
178    /// The HTTP version asked for. The response's version is recorded
179    /// instead when there is one.
180    pub protocol_version: Version,
181}
182
183/// One outgoing HTTP request, recorded as [`HttpClientLayer`] records it:
184/// a client span, trace context for the request's headers, and
185/// `http.client.request.duration`. For instrumenting an HTTP client that
186/// isn't a tower service:
187///
188/// ```
189/// use http::{HeaderMap, Method, StatusCode, Version};
190/// use oxtel_tower::{ClientCall, ClientRequestInfo};
191///
192/// # fn send(_: &HeaderMap) -> Result<StatusCode, ()> { Ok(StatusCode::OK) }
193/// let call = ClientCall::start(&ClientRequestInfo {
194///     method: &Method::GET,
195///     scheme: "https",
196///     server_address: Some("api.example"),
197///     server_port: None,
198///     path: "/items",
199///     protocol_version: Version::HTTP_11,
200/// });
201/// let mut headers = HeaderMap::new();
202/// call.inject_trace_context(&mut headers);
203/// // Send the request inside the span, so what it logs is part of it.
204/// match call.span().in_scope(|| send(&headers)) {
205///     Ok(status) => call.finish(status, Version::HTTP_11),
206///     Err(_) => call.fail("connect"),
207/// }
208/// ```
209///
210/// A call dropped without [`finish`](ClientCall::finish) or
211/// [`fail`](ClientCall::fail), as when its future is cancelled, ends its
212/// span without a status and records no duration.
213#[derive(Debug)]
214pub struct ClientCall {
215    span: Span,
216    started: Instant,
217    method: &'static str,
218    scheme: String,
219    address: Option<String>,
220    port: Option<u16>,
221    protocol_version: Version,
222    metrics: bool,
223}
224
225impl ClientCall {
226    /// Starts the request's span and its clock. Make the
227    /// [`HttpClientLayer`] or call [`describe_metrics`](crate::describe_metrics)
228    /// once first, so the duration is recorded in seconds with the
229    /// conventions' buckets.
230    pub fn start(info: &ClientRequestInfo<'_>) -> ClientCall {
231        let (method, method_original) = method_name(info.method);
232        let port = info.server_port.or(match info.scheme {
233            "https" => Some(443),
234            "http" => Some(80),
235            _ => None,
236        });
237        let span = tracing::info_span!(
238            target: "oxtel_tower",
239            "HTTP client request",
240            otel.name = if method == "_OTHER" { "HTTP" } else { method },
241            otel.kind = "client",
242            http.request.method = method,
243            http.request.method_original = method_original,
244            server.address = info.server_address,
245            server.port = port,
246            url.full = url_full(info.scheme, info.server_address, port, info.path),
247            network.protocol.version = tracing::field::Empty,
248            http.response.status_code = tracing::field::Empty,
249            error.type = tracing::field::Empty,
250            otel.status_code = tracing::field::Empty,
251        );
252        ClientCall {
253            span,
254            started: Instant::now(),
255            method,
256            scheme: info.scheme.to_string(),
257            address: info.server_address.map(str::to_string),
258            port,
259            protocol_version: info.protocol_version,
260            metrics: true,
261        }
262    }
263
264    /// Don't record `http.client.request.duration` for this request.
265    pub fn without_metrics(mut self) -> Self {
266        self.metrics = false;
267        self
268    }
269
270    /// The request's span. Send the request inside it.
271    pub fn span(&self) -> &Span {
272        &self.span
273    }
274
275    /// Adds W3C `traceparent` and `tracestate` to the request's headers, so
276    /// the server continues the trace: the client span's context, or the
277    /// caller's when the span is filtered out.
278    pub fn inject_trace_context(&self, headers: &mut HeaderMap) {
279        if let Some(cx) = span_context(&self.span).or_else(current_span_context) {
280            inject_trace_context(&cx, headers);
281        }
282    }
283
284    /// The response came back: records its status and HTTP version, marks
285    /// 4xx and 5xx as errors, and records the duration.
286    pub fn finish(self, status: StatusCode, version: Version) {
287        let status = status.as_u16();
288        self.span.record("http.response.status_code", status);
289        let error = (status >= 400).then(|| status.to_string());
290        self.end(Some(status), version, error);
291    }
292
293    /// No response came back. `error_type` names what went wrong, with few
294    /// enough values to be a metric label, such as `timeout` or `connect`.
295    pub fn fail(self, error_type: &str) {
296        let version = self.protocol_version;
297        self.end(None, version, Some(error_type.to_string()));
298    }
299
300    fn end(self, status: Option<u16>, version: Version, error: Option<String>) {
301        self.span
302            .record("network.protocol.version", protocol_version(version));
303        if let Some(error) = &error {
304            self.span.record("error.type", error.as_str());
305            self.span.record("otel.status_code", "error");
306        }
307        if !self.metrics {
308            return;
309        }
310        let mut labels = vec![
311            Label::new("http.request.method", self.method),
312            Label::new("url.scheme", self.scheme),
313        ];
314        if let Some(address) = self.address {
315            labels.push(Label::new("server.address", address));
316        }
317        if let Some(port) = self.port {
318            labels.push(Label::new("server.port", port.to_string()));
319        }
320        if let Some(status) = status {
321            labels.push(Label::new("http.response.status_code", status.to_string()));
322        }
323        if let Some(error) = error {
324            labels.push(Label::new("error.type", error));
325        }
326        metrics::histogram!("http.client.request.duration", labels)
327            .record(self.started.elapsed().as_secs_f64());
328    }
329}
330
331/// `url.full` without user information or query, which may hold secrets.
332fn url_full(scheme: &str, address: Option<&str>, port: Option<u16>, path: &str) -> String {
333    let mut url = format!("{scheme}://");
334    if let Some(host) = address {
335        if host.contains(':') {
336            url.push_str(&format!("[{host}]"));
337        } else {
338            url.push_str(host);
339        }
340    }
341    if let Some(port) = port {
342        url.push_str(&format!(":{port}"));
343    }
344    url.push_str(path);
345    url
346}