Skip to main content

encore/telemetry/
http.rs

1//! Server spans for HTTP handlers.
2
3use http::Request;
4
5use crate::opentelemetry::trace::{SpanBuilder, SpanKind, TraceContextExt, Tracer as _};
6use crate::opentelemetry::{Context, KeyValue};
7use encore_sdk_core::redaction::Redactor;
8
9/// Start a server span and return the context to use for the handler.
10///
11/// Run the handler future with [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context)
12/// and end the span when the request finishes. Only deployed policy can
13/// supply URL and header attributes. Without a policy route, the span is
14/// named by method alone (`HTTP` for an unrecognized method).
15///
16/// ```no_run
17/// use encore::opentelemetry::trace::{FutureExt, TraceContextExt};
18/// use encore::telemetry::http::start_span;
19///
20/// async fn handle(request: http::Request<()>) {
21///     let ctx = start_span(&request);
22///     async { /* handle the original request */ }.with_context(ctx.clone()).await;
23///     ctx.span().end();
24/// }
25/// ```
26pub fn start_span<B>(request: &Request<B>) -> Context {
27    let text = |name| {
28        request
29            .headers()
30            .get(name)
31            .and_then(|value| value.to_str().ok())
32    };
33    let mut parent = Context::new();
34    if let Some(remote) =
35        text("traceparent").and_then(|value| super::parse_traceparent(value, text("tracestate")))
36    {
37        parent = parent.with_remote_span_context(remote);
38    }
39    let parent = crate::reqctx::extract(&parent, request.headers());
40    let span = super::tracer(encore_sdk_core::telemetry::scope::SDK)
41        .build_with_context(builder(crate::runtime::core().redactor(), request), &parent);
42    parent.with_span(span)
43}
44
45fn builder<B>(redactor: &Redactor, request: &Request<B>) -> SpanBuilder {
46    let method = request.method();
47    let method_attr = method_attribute(method.as_str());
48    let mut attributes = vec![KeyValue::new("http.request.method", method_attr.to_owned())];
49    if method_attr == "_OTHER" {
50        attributes.push(KeyValue::new(
51            "http.request.method_original",
52            method.to_string(),
53        ));
54    }
55    let mut deployed = None;
56    if let Some(target) = request.uri().path_and_query() {
57        let http = redactor.http(method, target);
58        let url = http.request_url();
59        deployed = url.route;
60        if let Some(path) = url.path {
61            attributes.push(KeyValue::new("url.path", path));
62        }
63        if let Some(query) = url.query.filter(|q| !q.is_empty()) {
64            attributes.push(KeyValue::new("url.query", query));
65        }
66        if let Some(agent) = http.request_user_agent(request.headers()) {
67            attributes.push(KeyValue::new("user_agent.original", agent));
68        }
69    }
70    let route = deployed.as_deref().filter(|route| valid_route(route));
71    if let Some(route) = route {
72        attributes.push(KeyValue::new("http.route", route.to_owned()));
73    }
74    SpanBuilder::from_name(span_name(method_attr, route))
75        .with_kind(SpanKind::Server)
76        .with_attributes(attributes)
77}
78
79/// A standard request method or `_OTHER` for the semantic attribute.
80fn method_attribute(method: &str) -> &str {
81    match method {
82        "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
83        | "QUERY" => method,
84        _ => "_OTHER",
85    }
86}
87
88/// Whether a deployed template is application-relative and contains no query or fragment.
89fn valid_route(route: &str) -> bool {
90    route.starts_with('/')
91        && !route.starts_with("//")
92        && !route.contains(['?', '#'])
93        && !route.chars().any(|c| c.is_control() || c.is_whitespace())
94}
95
96/// The exported span name for a request and its selected route.
97fn span_name(method: &str, route: Option<&str>) -> String {
98    let method = match method {
99        "_OTHER" => "HTTP",
100        method => method,
101    };
102    match route {
103        Some(route) => format!("{method} {route}"),
104        None => method.to_owned(),
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn span_metadata_uses_only_the_safe_target() {
114        let config = serde_json::from_value(serde_json::json!({
115            "deployment": {"hosted_services": [{"name": "app", "routes": [{
116                "path": "/items/{id}", "methods": ["GET"], "endpoint": {"name": "items", "recording": {"redaction": {
117                    "path_params": ["id"], "query": ["token"], "request_headers": ["user-agent"]
118                }}}
119            }]}]}
120        })).unwrap();
121        let redactor = Redactor::from_runtime_config(&config);
122        let request = http::Request::get("/items/private?token=secret")
123            .header("user-agent", "synthetic-agent")
124            .body(())
125            .unwrap();
126        let span = builder(&redactor, &request);
127        assert_eq!(span.name, "GET /items/{id}");
128        let attrs = span.attributes.unwrap();
129        assert!(attrs.iter().any(
130            |attr| attr.key.as_str() == "url.path" && attr.value.as_str() == "/items/REDACTED"
131        ));
132        for (key, value) in [
133            ("url.query", "token=REDACTED"),
134            ("user_agent.original", "[REDACTED]"),
135        ] {
136            assert!(
137                attrs
138                    .iter()
139                    .any(|attr| attr.key.as_str() == key && attr.value.as_str() == value)
140            );
141        }
142        assert!(attrs.iter().all(|attr| attr.key.as_str() != "url.full"));
143        assert_eq!(request.uri().path(), "/items/private");
144        assert_eq!(request.headers()["user-agent"], "synthetic-agent");
145        let request = http::Request::get("/unknown/private").body(()).unwrap();
146        let unknown = builder(&redactor, &request);
147        assert_eq!(unknown.name, "GET");
148        assert!(
149            unknown
150                .attributes
151                .unwrap()
152                .iter()
153                .all(|attr| attr.key.as_str() != "url.path")
154        );
155    }
156
157    #[test]
158    fn unknown_method_without_schema() {
159        let redactor = Redactor::from_runtime_config(&Default::default());
160        let request = Request::builder()
161            .method("BREW")
162            .uri("/orders/synthetic")
163            .body(())
164            .unwrap();
165        assert_eq!(builder(&redactor, &request).name, "HTTP");
166    }
167}