Skip to main content

miden_node_utils/tracing/
grpc.rs

1use tracing::field;
2
3use crate::tracing::OpenTelemetrySpanExt;
4
5/// Returns a [`trace_fn`](tonic::transport::server::Server) implementation for gRPC requests
6/// which adds open-telemetry information to the span.
7///
8/// Creates an `info` span following the open-telemetry standard: `{service}/{method}`.
9/// The span name is dynamically set using the HTTP path via the `otel.name` field.
10/// Additionally also pulls in remote tracing context which allows the server trace to be connected
11/// to the client's origin trace.
12#[track_caller]
13pub fn grpc_trace_fn<T>(request: &http::Request<T>) -> tracing::Span {
14    // A gRPC request's path ends with `../<service>/<method>`.
15    let mut path_segments = request.uri().path().rsplit('/');
16
17    let method = path_segments.next().unwrap_or_default();
18    let service = path_segments.next().unwrap_or_default();
19
20    // Create a span with a generic, static name. Fields to be recorded after needs to be
21    // initialized as empty since otherwise the assignment will have no effect.
22    let span = tracing::info_span!(
23        "rpc",
24        otel.name = field::Empty,
25        rpc.service = service,
26        rpc.method = method
27    );
28
29    // Set the span name via otel.name
30    let otel_name = format!("{service}/{method}");
31    span.record("otel.name", otel_name);
32
33    // Pull the open-telemetry parent context using the HTTP extractor
34    let otel_ctx = opentelemetry::global::get_text_map_propagator(|propagator| {
35        propagator.extract(&MetadataExtractor(&tonic::metadata::MetadataMap::from_headers(
36            request.headers().clone(),
37        )))
38    });
39    let _ = tracing_opentelemetry::OpenTelemetrySpanExt::set_parent(&span, otel_ctx);
40
41    // Adds various network attributes to the span, including remote address and port.
42    //
43    // See [server attributes](https://opentelemetry.io/docs/specs/semconv/rpc/rpc-spans/#server-attributes).
44
45    // Set HTTP attributes.
46    span.set_attribute("rpc.system", "grpc");
47    if let Some(host) = request.uri().host() {
48        span.set_attribute("server.address", host);
49    }
50    if let Some(host_port) = request.uri().port() {
51        span.set_attribute("server.port", host_port.as_u16());
52    }
53    let remote_addr = request
54        .extensions()
55        .get::<tonic::transport::server::TcpConnectInfo>()
56        .and_then(tonic::transport::server::TcpConnectInfo::remote_addr);
57    if let Some(addr) = remote_addr {
58        span.set_attribute("client.address", addr.ip());
59        span.set_attribute("client.port", addr.port());
60        span.set_attribute("network.peer.address", addr.ip());
61        span.set_attribute("network.peer.port", addr.port());
62        span.set_attribute("network.transport", "tcp");
63        match addr.ip() {
64            std::net::IpAddr::V4(_) => span.set_attribute("network.type", "ipv4"),
65            std::net::IpAddr::V6(_) => span.set_attribute("network.type", "ipv6"),
66        }
67    }
68
69    span
70}
71
72/// Injects open-telemetry remote context into traces.
73#[derive(Copy, Clone)]
74pub struct OtelInterceptor;
75
76impl tonic::service::Interceptor for OtelInterceptor {
77    fn call(
78        &mut self,
79        mut request: tonic::Request<()>,
80    ) -> Result<tonic::Request<()>, tonic::Status> {
81        use tracing_opentelemetry::OpenTelemetrySpanExt;
82        let ctx = tracing::Span::current().context();
83        opentelemetry::global::get_text_map_propagator(|propagator| {
84            propagator.inject_context(&ctx, &mut MetadataInjector(request.metadata_mut()));
85        });
86
87        Ok(request)
88    }
89}
90
91struct MetadataExtractor<'a>(&'a tonic::metadata::MetadataMap);
92impl opentelemetry::propagation::Extractor for MetadataExtractor<'_> {
93    /// Get a value for a key from the `MetadataMap`.  If the value can't be converted to &str,
94    /// returns None
95    fn get(&self, key: &str) -> Option<&str> {
96        self.0.get(key).and_then(|metadata| metadata.to_str().ok())
97    }
98
99    /// Collect all the keys from the `MetadataMap`.
100    fn keys(&self) -> Vec<&str> {
101        self.0
102            .keys()
103            .map(|key| match key {
104                tonic::metadata::KeyRef::Ascii(v) => v.as_str(),
105                tonic::metadata::KeyRef::Binary(v) => v.as_str(),
106            })
107            .collect::<Vec<_>>()
108    }
109}
110
111struct MetadataInjector<'a>(&'a mut tonic::metadata::MetadataMap);
112impl opentelemetry::propagation::Injector for MetadataInjector<'_> {
113    /// Set a key and value in the `MetadataMap`.  Does nothing if the key or value are not valid
114    /// inputs
115    fn set(&mut self, key: &str, value: String) {
116        if let Ok(key) = tonic::metadata::MetadataKey::from_bytes(key.as_bytes())
117            && let Ok(val) = tonic::metadata::MetadataValue::try_from(&value)
118        {
119            self.0.insert(key, val);
120        }
121    }
122}