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