Skip to main content

saluki_components/common/otlp/
proxy.rs

1//! Streaming proxy from the OTLP servers to an upstream OTLP receiver.
2//!
3//! A proxied request isn't decoded. The proxy streams it to the upstream receiver with only the changes that forwarding
4//! needs, and streams the upstream response back unchanged: status, headers, body, and trailers. When the upstream
5//! receiver doesn't answer, the client gets an error. The proxy never retries a request.
6
7use std::sync::{
8    atomic::{AtomicBool, Ordering},
9    Arc,
10};
11use std::time::Duration;
12
13use axum::extract::Request;
14use axum::response::{IntoResponse as _, Response};
15use axum::routing::{any, MethodRouter};
16use http::header::{self, HeaderMap, HeaderValue};
17use http::uri::Uri;
18use http::Version;
19use metrics::Counter;
20use rustls::RootCertStore;
21use saluki_error::{generic_error, ErrorContext as _, GenericError};
22use saluki_io::net::client::http::{HttpClient, HttpProtocol};
23use saluki_metrics::MetricsBuilder;
24use tonic::Status;
25use tracing::{debug, info, warn};
26
27use super::Signal;
28use crate::common::proxy::{strip_hop_by_hop_headers, upstream_uri, Destination, ForwardError, UpstreamClient};
29
30/// Bound on connecting to the upstream receiver.
31const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
32
33/// Where the proxy forwards requests, for each protocol.
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct OtlpProxyDestinations {
36    /// Upstream OTLP/gRPC receiver. The proxy speaks HTTP/2 to it with prior knowledge.
37    ///
38    /// `None` if no gRPC server proxies requests.
39    pub grpc: Option<Destination>,
40
41    /// Upstream OTLP/HTTP receiver. The proxy speaks HTTP/1.1 to it.
42    ///
43    /// `None` if no HTTP server proxies requests.
44    pub http: Option<Destination>,
45}
46
47/// Streams OTLP requests to the upstream receivers.
48pub(crate) struct OtlpProxy {
49    grpc: Option<Arc<Upstream>>,
50    http: Option<Arc<Upstream>>,
51    metrics_builder: MetricsBuilder,
52}
53
54impl OtlpProxy {
55    /// Creates a proxy to `destinations`.
56    ///
57    /// # Errors
58    ///
59    /// If an HTTP client can't be built, an error is returned.
60    pub(crate) fn new(
61        destinations: &OtlpProxyDestinations, metrics_builder: MetricsBuilder,
62    ) -> Result<Self, GenericError> {
63        Self::with_connect_timeout(destinations, metrics_builder, CONNECT_TIMEOUT)
64    }
65
66    fn with_connect_timeout(
67        destinations: &OtlpProxyDestinations, metrics_builder: MetricsBuilder, connect_timeout: Duration,
68    ) -> Result<Self, GenericError> {
69        let upstream = |protocol, destination: &Option<Destination>| {
70            destination
71                .as_ref()
72                .map(|destination| Upstream::new(protocol, destination, connect_timeout).map(Arc::new))
73                .transpose()
74        };
75        Ok(Self {
76            grpc: upstream(Protocol::Grpc, &destinations.grpc)?,
77            http: upstream(Protocol::Http, &destinations.http)?,
78            metrics_builder,
79        })
80    }
81
82    /// Returns the service that proxies the gRPC requests of `signal`.
83    ///
84    /// # Errors
85    ///
86    /// If the proxy has no gRPC destination, an error is returned.
87    pub(crate) fn grpc_service(&self, signal: Signal) -> Result<MethodRouter, GenericError> {
88        let upstream = self.grpc.as_ref().ok_or_else(|| {
89            generic_error!("An OTLP signal is proxied over gRPC, but the OTLP proxy has no gRPC destination.")
90        })?;
91        Ok(SignalProxy::new(Arc::clone(upstream), signal, &self.metrics_builder).into_service())
92    }
93
94    /// Returns the service that proxies the HTTP requests of `signal`.
95    ///
96    /// # Errors
97    ///
98    /// If the proxy has no HTTP destination, an error is returned.
99    pub(crate) fn http_service(&self, signal: Signal) -> Result<MethodRouter, GenericError> {
100        let upstream = self.http.as_ref().ok_or_else(|| {
101            generic_error!("An OTLP signal is proxied over HTTP, but the OTLP proxy has no HTTP destination.")
102        })?;
103        Ok(SignalProxy::new(Arc::clone(upstream), signal, &self.metrics_builder).into_service())
104    }
105}
106
107/// Protocol of an upstream receiver.
108#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109enum Protocol {
110    Grpc,
111    Http,
112}
113
114impl Protocol {
115    const fn as_str(self) -> &'static str {
116        match self {
117            Self::Grpc => "grpc",
118            Self::Http => "http",
119        }
120    }
121
122    /// Returns the response to a request that the upstream receiver didn't answer.
123    fn error_response(self, error: ForwardError) -> Response {
124        match (self, error) {
125            // `into_http` makes a trailers-only response, which gRPC clients read as the status of the call.
126            (Self::Grpc, ForwardError::Unreachable) => {
127                Status::unavailable("The upstream OTLP receiver is unreachable.").into_http()
128            }
129            (Self::Grpc, _) => Status::internal("The request couldn't be forwarded.").into_http(),
130            (Self::Http, error) => error.into_response(),
131        }
132    }
133}
134
135/// An upstream receiver, shared by every signal of one protocol.
136struct Upstream {
137    protocol: Protocol,
138    client: UpstreamClient,
139
140    /// Scheme and authority of the URI of each request. For a Unix domain socket destination the client ignores the
141    /// authority.
142    base_uri: Uri,
143
144    destination: Destination,
145
146    /// Whether the last request failed. Only the first failure after a success logs a warning.
147    unreachable: AtomicBool,
148}
149
150impl Upstream {
151    fn new(protocol: Protocol, destination: &Destination, connect_timeout: Duration) -> Result<Self, GenericError> {
152        let builder = HttpClient::builder()
153            // The upstream receiver serves plaintext, so an empty root store avoids loading the platform's certificates.
154            .with_tls_config(|builder| builder.with_root_cert_store(RootCertStore::empty()))
155            .with_http_protocol(match protocol {
156                Protocol::Grpc => HttpProtocol::Http2,
157                Protocol::Http => HttpProtocol::Http1,
158            })
159            .with_connect_timeout(connect_timeout)
160            // Clients set their own deadlines, such as `grpc-timeout`, and the upstream receiver enforces them.
161            .without_request_timeout()
162            // The proxy retries no request itself. This setting resends only a request that never started on a reused
163            // connection, so the upstream receiver can't have seen it.
164            .with_hyper_config(|builder| {
165                builder.retry_canceled_requests(true);
166            });
167
168        let base_uri = destination
169            .base_uri()
170            .with_error_context(|| format!("Invalid OTLP proxy destination {destination:?}."))?;
171        let builder = destination.configure_client(builder);
172
173        Ok(Self {
174            protocol,
175            client: UpstreamClient::new(builder.build()?),
176            base_uri,
177            destination: destination.clone(),
178            unreachable: AtomicBool::new(false),
179        })
180    }
181
182    /// Forwards `request` and returns the upstream response.
183    ///
184    /// # Errors
185    ///
186    /// If the request's path can't be carried over, or the upstream receiver doesn't answer, an error is returned.
187    async fn forward(&self, signal: Signal, request: Request) -> Result<Response, ForwardError> {
188        let (mut parts, body) = request.into_parts();
189
190        parts.uri = match upstream_uri(&self.base_uri, parts.uri.path_and_query()) {
191            Ok(uri) => uri,
192            Err(e) => {
193                debug!(error = %e, signal = signal.as_str(), "Failed to build the upstream URI of an OTLP request.");
194                return Err(ForwardError::InvalidUri);
195            }
196        };
197
198        // HTTP/2 allows `TE` with the value `trailers` only, and gRPC uses it to say that the client reads trailers.
199        let keep_te = self.protocol == Protocol::Grpc && accepts_trailers(&parts.headers);
200        strip_hop_by_hop_headers(&mut parts.headers);
201        if keep_te {
202            parts.headers.insert(header::TE, HeaderValue::from_static("trailers"));
203        }
204        // The client derives `Host`, or `:authority` over HTTP/2, from the upstream URI.
205        parts.headers.remove(header::HOST);
206        // The OTLP/HTTP server also accepts HTTP/2, but the upstream client refuses an HTTP/2 request over HTTP/1.1.
207        parts.version = match self.protocol {
208            Protocol::Grpc => Version::HTTP_2,
209            Protocol::Http => Version::HTTP_11,
210        };
211
212        match self.client.send(http::Request::from_parts(parts, body)).await {
213            Ok(response) => {
214                if self.unreachable.swap(false, Ordering::Relaxed) {
215                    info!(
216                        destination = ?self.destination,
217                        protocol = self.protocol.as_str(),
218                        "The upstream OTLP receiver is reachable again."
219                    );
220                }
221                Ok(response)
222            }
223            Err(e) => {
224                if self.unreachable.swap(true, Ordering::Relaxed) {
225                    debug!(
226                        error = %e,
227                        destination = ?self.destination,
228                        protocol = self.protocol.as_str(),
229                        signal = signal.as_str(),
230                        "Failed to forward an OTLP request to the upstream receiver."
231                    );
232                } else {
233                    warn!(
234                        error = %e,
235                        destination = ?self.destination,
236                        protocol = self.protocol.as_str(),
237                        signal = signal.as_str(),
238                        "Failed to forward an OTLP request to the upstream receiver. Proxied requests fail until it is reachable again."
239                    );
240                }
241                Err(ForwardError::Unreachable)
242            }
243        }
244    }
245}
246
247/// Returns `true` if the `TE` header lists `trailers`.
248fn accepts_trailers(headers: &HeaderMap) -> bool {
249    headers
250        .get_all(header::TE)
251        .iter()
252        .filter_map(|value| value.to_str().ok())
253        .flat_map(|value| value.split(','))
254        .any(|coding| coding.trim().eq_ignore_ascii_case("trailers"))
255}
256
257/// Proxies the requests of one signal over one protocol.
258#[derive(Clone)]
259struct SignalProxy {
260    upstream: Arc<Upstream>,
261    signal: Signal,
262
263    /// Requests that the upstream receiver answered, whatever the status of its answer.
264    requests_relayed: Counter,
265
266    /// Requests that the upstream receiver never answered, such as when it was unreachable.
267    requests_failed: Counter,
268}
269
270impl SignalProxy {
271    fn new(upstream: Arc<Upstream>, signal: Signal, metrics_builder: &MetricsBuilder) -> Self {
272        let tags = [("signal", signal.as_str()), ("protocol", upstream.protocol.as_str())];
273        Self {
274            requests_relayed: metrics_builder.register_counter_with_tags("component_requests_relayed_total", tags),
275            requests_failed: metrics_builder.register_counter_with_tags("component_requests_failed_total", tags),
276            upstream,
277            signal,
278        }
279    }
280
281    fn into_service(self) -> MethodRouter {
282        any(move |request: Request| {
283            let proxy = self.clone();
284            async move { proxy.forward(request).await }
285        })
286    }
287
288    async fn forward(&self, request: Request) -> Response {
289        match self.upstream.forward(self.signal, request).await {
290            Ok(response) => {
291                self.requests_relayed.increment(1);
292                response
293            }
294            Err(error) => {
295                self.requests_failed.increment(1);
296                self.upstream.protocol.error_response(error)
297            }
298        }
299    }
300}
301
302#[cfg(test)]
303mod tests;