Skip to main content

oxtel_tower/
request.rs

1//! What the semantic conventions record about a request.
2
3use std::fmt;
4
5use http::{Method, Request, Version};
6
7/// The method as the conventions name it: one of the HTTP methods, or
8/// `_OTHER` with the method as sent, so made-up methods can't grow label
9/// sets.
10pub(crate) fn method_name(method: &Method) -> (&'static str, Option<&str>) {
11    let known = match *method {
12        Method::GET => "GET",
13        Method::HEAD => "HEAD",
14        Method::POST => "POST",
15        Method::PUT => "PUT",
16        Method::DELETE => "DELETE",
17        Method::CONNECT => "CONNECT",
18        Method::OPTIONS => "OPTIONS",
19        Method::TRACE => "TRACE",
20        Method::PATCH => "PATCH",
21        // A known method in the conventions since v1.44, though `http` has
22        // no constant for it.
23        _ if method.as_str() == "QUERY" => "QUERY",
24        _ => return ("_OTHER", Some(method.as_str())),
25    };
26    (known, None)
27}
28
29/// `network.protocol.version`.
30pub(crate) fn protocol_version(version: Version) -> &'static str {
31    match version {
32        Version::HTTP_09 => "0.9",
33        Version::HTTP_10 => "1.0",
34        Version::HTTP_11 => "1.1",
35        Version::HTTP_2 => "2",
36        Version::HTTP_3 => "3",
37        _ => "_OTHER",
38    }
39}
40
41/// The host and port a request was addressed to: the URI's authority, else
42/// the `Host` header. The port is left out when neither gives one.
43pub(crate) fn server_address<B>(req: &Request<B>) -> (Option<&str>, Option<u16>) {
44    let authority = req
45        .uri()
46        .authority()
47        .map(|a| a.as_str())
48        .or_else(|| req.headers().get(http::header::HOST)?.to_str().ok());
49    let Some(authority) = authority else {
50        return (None, None);
51    };
52    let authority = authority
53        .rsplit_once('@')
54        .map_or(authority, |(_, host)| host);
55    if let Some(v6) = authority.strip_prefix('[') {
56        let Some((host, rest)) = v6.split_once(']') else {
57            return (None, None);
58        };
59        return (
60            Some(host),
61            rest.strip_prefix(':').and_then(|p| p.parse().ok()),
62        );
63    }
64    match authority.rsplit_once(':') {
65        Some((host, port)) => (Some(host), port.parse().ok()),
66        None => (Some(authority), None),
67    }
68}
69
70/// What an incoming request's span records, as the HTTP semantic
71/// conventions name it. Handed to a span-making hook; see
72/// [`server_span!`](crate::server_span).
73#[derive(Debug)]
74pub struct RequestInfo<'a> {
75    /// `http.request.method`: a known method, or `_OTHER`.
76    pub method: &'static str,
77    /// `http.request.method_original`, for `_OTHER`.
78    pub method_original: Option<&'a str>,
79    /// `url.path`. The query isn't recorded; it may hold secrets.
80    pub path: &'a str,
81    /// `url.scheme`.
82    pub scheme: &'a str,
83    /// `http.route`: the route template that matched, such as
84    /// `/items/{id}`, if the layer knows it.
85    pub route: Option<&'a str>,
86    /// `server.address`, from the URI or the `Host` header.
87    pub server_address: Option<&'a str>,
88    /// `server.port`.
89    pub server_port: Option<u16>,
90    /// `network.protocol.version`, such as `1.1` or `2`.
91    pub protocol_version: &'static str,
92    /// `user_agent.original`.
93    pub user_agent: Option<&'a str>,
94}
95
96impl RequestInfo<'_> {
97    /// The span's name: `{method} {route}`, or just the method without a
98    /// route; `HTTP` stands for a method outside the standard ones.
99    pub fn span_name(&self) -> SpanName<'_> {
100        SpanName {
101            method: if self.method == "_OTHER" {
102                "HTTP"
103            } else {
104                self.method
105            },
106            route: self.route,
107        }
108    }
109}
110
111/// A span name, formatted without allocating until it's recorded.
112#[derive(Debug, Clone, Copy)]
113pub struct SpanName<'a> {
114    method: &'a str,
115    route: Option<&'a str>,
116}
117
118impl fmt::Display for SpanName<'_> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self.route {
121            Some(route) => write!(f, "{} {route}", self.method),
122            None => f.write_str(self.method),
123        }
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn request(uri: &str, host: Option<&str>) -> Request<()> {
132        let mut b = Request::builder().uri(uri);
133        if let Some(host) = host {
134            b = b.header("host", host);
135        }
136        b.body(()).unwrap()
137    }
138
139    #[test]
140    fn addresses_come_from_the_authority_or_host() {
141        assert_eq!(
142            server_address(&request("/x", Some("api.example:8080"))),
143            (Some("api.example"), Some(8080))
144        );
145        assert_eq!(
146            server_address(&request("/x", Some("api.example"))),
147            (Some("api.example"), None)
148        );
149        assert_eq!(
150            server_address(&request("http://u:p@[::1]:9/x", None)),
151            (Some("::1"), Some(9))
152        );
153        assert_eq!(server_address(&request("/x", None)), (None, None));
154    }
155
156    #[test]
157    fn unknown_methods_are_other() {
158        assert_eq!(method_name(&Method::GET), ("GET", None));
159        let purge = Method::from_bytes(b"PURGE").unwrap();
160        assert_eq!(method_name(&purge), ("_OTHER", Some("PURGE")));
161        let query = Method::from_bytes(b"QUERY").unwrap();
162        assert_eq!(method_name(&query), ("QUERY", None));
163    }
164}