encore-dev 2.0.0-beta.17

Rust SDK for Encore applications
Documentation
//! Server spans for HTTP handlers.

use http::Request;

use crate::opentelemetry::trace::{SpanBuilder, SpanKind, TraceContextExt, Tracer as _};
use crate::opentelemetry::{Context, KeyValue};
use encore_sdk_core::redaction::Redactor;

/// Start a server span and return the context to use for the handler.
///
/// Run the handler future with [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context)
/// and end the span when the request finishes. Only deployed policy can
/// supply URL and header attributes. Without a policy route, the span is
/// named by method alone (`HTTP` for an unrecognized method).
///
/// ```no_run
/// use encore::opentelemetry::trace::{FutureExt, TraceContextExt};
/// use encore::telemetry::http::start_span;
///
/// async fn handle(request: http::Request<()>) {
///     let ctx = start_span(&request);
///     async { /* handle the original request */ }.with_context(ctx.clone()).await;
///     ctx.span().end();
/// }
/// ```
pub fn start_span<B>(request: &Request<B>) -> Context {
    let text = |name| {
        request
            .headers()
            .get(name)
            .and_then(|value| value.to_str().ok())
    };
    let mut parent = Context::new();
    if let Some(remote) =
        text("traceparent").and_then(|value| super::parse_traceparent(value, text("tracestate")))
    {
        parent = parent.with_remote_span_context(remote);
    }
    let parent = crate::reqctx::extract(&parent, request.headers());
    let span = super::tracer("encore.server")
        .build_with_context(builder(crate::runtime::core().redactor(), request), &parent);
    parent.with_span(span)
}

fn builder<B>(redactor: &Redactor, request: &Request<B>) -> SpanBuilder {
    let method = request.method();
    let method_attr = method_attribute(method.as_str());
    let mut attributes = vec![KeyValue::new("http.request.method", method_attr.to_owned())];
    if method_attr == "_OTHER" {
        attributes.push(KeyValue::new(
            "http.request.method_original",
            method.to_string(),
        ));
    }
    let mut deployed = None;
    if let Some(target) = request.uri().path_and_query() {
        let http = redactor.http(method, target);
        let url = http.request_url();
        deployed = url.route;
        if let Some(path) = url.path {
            attributes.push(KeyValue::new("url.path", path));
        }
        if let Some(query) = url.query.filter(|q| !q.is_empty()) {
            attributes.push(KeyValue::new("url.query", query));
        }
        if let Some(agent) = http.request_user_agent(request.headers()) {
            attributes.push(KeyValue::new("user_agent.original", agent));
        }
    }
    let route = deployed.as_deref().filter(|route| valid_route(route));
    if let Some(route) = route {
        attributes.push(KeyValue::new("http.route", route.to_owned()));
    }
    SpanBuilder::from_name(span_name(method_attr, route))
        .with_kind(SpanKind::Server)
        .with_attributes(attributes)
}

/// A standard request method or `_OTHER` for the semantic attribute.
fn method_attribute(method: &str) -> &str {
    match method {
        "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
        | "QUERY" => method,
        _ => "_OTHER",
    }
}

/// Whether a deployed template is application-relative and contains no query or fragment.
fn valid_route(route: &str) -> bool {
    route.starts_with('/')
        && !route.starts_with("//")
        && !route.contains(['?', '#'])
        && !route.chars().any(|c| c.is_control() || c.is_whitespace())
}

/// The exported span name for a request and its selected route.
fn span_name(method: &str, route: Option<&str>) -> String {
    let method = match method {
        "_OTHER" => "HTTP",
        method => method,
    };
    match route {
        Some(route) => format!("{method} {route}"),
        None => method.to_owned(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn span_metadata_uses_only_the_safe_target() {
        let config = serde_json::from_value(serde_json::json!({
            "deployment": {"hosted_services": [{"name": "app", "routes": [{
                "path": "/items/{id}", "methods": ["GET"], "endpoint": {"name": "items", "recording": {"redaction": {
                    "path_params": ["id"], "query": ["token"], "request_headers": ["user-agent"]
                }}}
            }]}]}
        })).unwrap();
        let redactor = Redactor::from_runtime_config(&config);
        let request = http::Request::get("/items/private?token=secret")
            .header("user-agent", "synthetic-agent")
            .body(())
            .unwrap();
        let span = builder(&redactor, &request);
        assert_eq!(span.name, "GET /items/{id}");
        let attrs = span.attributes.unwrap();
        assert!(attrs.iter().any(
            |attr| attr.key.as_str() == "url.path" && attr.value.as_str() == "/items/REDACTED"
        ));
        for (key, value) in [
            ("url.query", "token=REDACTED"),
            ("user_agent.original", "[REDACTED]"),
        ] {
            assert!(attrs
                .iter()
                .any(|attr| attr.key.as_str() == key && attr.value.as_str() == value));
        }
        assert!(attrs.iter().all(|attr| attr.key.as_str() != "url.full"));
        assert_eq!(request.uri().path(), "/items/private");
        assert_eq!(request.headers()["user-agent"], "synthetic-agent");
        let request = http::Request::get("/unknown/private").body(()).unwrap();
        let unknown = builder(&redactor, &request);
        assert_eq!(unknown.name, "GET");
        assert!(unknown
            .attributes
            .unwrap()
            .iter()
            .all(|attr| attr.key.as_str() != "url.path"));
    }

    #[test]
    fn unknown_method_without_schema() {
        let redactor = Redactor::from_runtime_config(&Default::default());
        let request = Request::builder()
            .method("BREW")
            .uri("/orders/synthetic")
            .body(())
            .unwrap();
        assert_eq!(builder(&redactor, &request).name, "HTTP");
    }
}