Skip to main content

saluki_components/common/otlp/
receiver.rs

1//! OTLP receiver settings of the OTLP source.
2
3use std::time::Duration;
4
5use saluki_error::{generic_error, GenericError};
6use saluki_io::net::{server::http::Http2Config, ListenAddress};
7
8use super::{CorsConfiguration, OtlpTlsConfiguration};
9
10/// Settings of the OTLP receiver's gRPC and HTTP servers.
11#[derive(Clone, Debug, PartialEq)]
12pub struct OtlpReceiver {
13    /// gRPC server settings.
14    pub grpc: OtlpGrpcReceiver,
15
16    /// HTTP server settings.
17    pub http: OtlpHttpReceiver,
18}
19
20impl OtlpReceiver {
21    /// Checks that at least one server has an endpoint.
22    ///
23    /// A caller that checks for an endpoint first never builds a source that fails this check.
24    ///
25    /// # Errors
26    ///
27    /// Returns an error if the gRPC and HTTP endpoints are both empty.
28    pub(crate) fn check_endpoints(&self) -> Result<(), GenericError> {
29        if self.grpc.endpoint.is_empty() && self.http.endpoint.is_empty() {
30            return Err(generic_error!(
31                "The OTLP gRPC and HTTP receiver endpoints are both empty, so no OTLP server can start. Set \
32                 `otlp_config.receiver.protocols.grpc.endpoint` or `otlp_config.receiver.protocols.http.endpoint`."
33            ));
34        }
35
36        Ok(())
37    }
38
39    /// Builds the TLS configurations of the HTTP and gRPC servers, in that order.
40    ///
41    /// A server with an empty endpoint doesn't start, so its TLS settings are not validated and it gets no
42    /// configuration.
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if a server with an endpoint has TLS settings that [`OtlpReceiverTls::build`] rejects.
47    pub(crate) fn tls_configurations(
48        &self,
49    ) -> Result<(Option<OtlpTlsConfiguration>, Option<OtlpTlsConfiguration>), GenericError> {
50        let http = if self.http.endpoint.is_empty() {
51            None
52        } else {
53            self.http.tls.build()?
54        };
55        let grpc = if self.grpc.endpoint.is_empty() {
56            None
57        } else {
58            self.grpc.tls.build()?
59        };
60
61        Ok((http, grpc))
62    }
63}
64
65/// Settings of the OTLP receiver's gRPC server.
66#[derive(Clone, Debug, PartialEq)]
67pub struct OtlpGrpcReceiver {
68    /// Address the server listens on, without a scheme. If empty, the server doesn't start.
69    pub endpoint: String,
70
71    /// Maximum size of a received message, in MiB.
72    pub max_recv_msg_size_mib: u64,
73
74    /// Transport the server listens with.
75    pub transport: GrpcTransport,
76
77    /// Maximum number of concurrent streams per connection. If set to `0`, the number is not limited.
78    pub max_concurrent_streams: u32,
79
80    /// Keepalive and connection age settings.
81    pub keepalive: OtlpKeepalive,
82
83    /// TLS settings.
84    pub tls: OtlpReceiverTls,
85}
86
87/// Transport of the OTLP receiver's gRPC server.
88#[derive(Clone, Copy, Debug, Eq, PartialEq)]
89pub enum GrpcTransport {
90    /// TCP socket.
91    Tcp,
92
93    /// Unix domain socket.
94    Unix,
95}
96
97impl GrpcTransport {
98    /// Returns the listen address scheme of this transport.
99    pub const fn as_str(self) -> &'static str {
100        match self {
101            Self::Tcp => "tcp",
102            Self::Unix => "unix",
103        }
104    }
105}
106
107/// Settings of the OTLP receiver's HTTP server.
108#[derive(Clone, Debug, PartialEq)]
109pub struct OtlpHttpReceiver {
110    /// Address the server listens on, without a scheme. If empty, the server doesn't start.
111    pub endpoint: String,
112
113    /// Listen address scheme of `endpoint`, such as `tcp` or `unix`.
114    pub transport: String,
115
116    /// CORS settings.
117    pub cors: CorsConfiguration,
118
119    /// TLS settings.
120    pub tls: OtlpReceiverTls,
121
122    /// Maximum size of a request body, in bytes. If set to `0`, a default of 20 MiB applies.
123    pub max_request_body_size: u64,
124}
125
126/// Keepalive and connection age settings of the OTLP receiver's gRPC server.
127#[derive(Clone, Debug, PartialEq)]
128pub struct OtlpKeepalive {
129    /// Maximum age of a connection. If set to zero, connection age is not limited.
130    pub max_connection_age: Duration,
131
132    /// Grace period after `max_connection_age` for in-flight requests. If set to zero, the grace period is not
133    /// limited.
134    pub max_connection_age_grace: Duration,
135
136    /// Interval between keepalive pings.
137    pub time: Duration,
138
139    /// Time to wait for a keepalive ping acknowledgement.
140    pub timeout: Duration,
141}
142
143/// TLS file paths of an OTLP receiver server.
144#[derive(Clone, Debug, Eq, PartialEq)]
145pub struct OtlpReceiverTls {
146    /// Server certificate file. Empty if unset.
147    pub cert_file: String,
148
149    /// Server private key file. Empty if unset.
150    pub key_file: String,
151
152    /// CA certificate file used to verify client certificates. Empty if unset.
153    pub ca_file: String,
154}
155
156impl OtlpReceiverTls {
157    /// Builds a server TLS configuration, if TLS is enabled.
158    ///
159    /// TLS is enabled when both `cert_file` and `key_file` are non-empty. When `ca_file` is also non-empty, the server
160    /// requests client certificates and verifies them against the CA certificates in that file, but does not require a
161    /// client certificate (optional verification).
162    ///
163    /// # Errors
164    ///
165    /// Returns an error if any TLS field is set without the others required to form a valid TLS configuration. Both
166    /// `cert_file` and `key_file` must be provided together to enable TLS, and `ca_file` must not be set without them.
167    /// Setting only a subset is treated as a configuration error rather than silently downgrading to plaintext.
168    pub(crate) fn build(&self) -> Result<Option<OtlpTlsConfiguration>, GenericError> {
169        match (self.cert_file.is_empty(), self.key_file.is_empty()) {
170            (true, true) => {
171                if !self.ca_file.is_empty() {
172                    Err(generic_error!(
173                        "OTLP receiver TLS `ca_file` is set but `cert_file` and `key_file` are empty. All three must \
174                         be provided together, or `ca_file` must be omitted when TLS is disabled."
175                    ))
176                } else {
177                    Ok(None)
178                }
179            }
180            (false, false) => {
181                let mut config = OtlpTlsConfiguration::new(self.cert_file.clone().into(), self.key_file.clone().into());
182                if !self.ca_file.is_empty() {
183                    config = config.with_ca_file(self.ca_file.clone().into());
184                }
185                Ok(Some(config))
186            }
187            (true, false) => Err(generic_error!(
188                "OTLP receiver TLS `key_file` is set but `cert_file` is empty. Both must be provided to enable TLS."
189            )),
190            (false, true) => Err(generic_error!(
191                "OTLP receiver TLS `cert_file` is set but `key_file` is empty. Both must be provided to enable TLS."
192            )),
193        }
194    }
195}
196
197impl OtlpGrpcReceiver {
198    /// Returns the address the server listens on, or `None` if the endpoint is empty.
199    ///
200    /// # Errors
201    ///
202    /// If the transport and endpoint don't make a valid listen address, an error is returned.
203    pub fn listen_address(&self) -> Result<Option<ListenAddress>, GenericError> {
204        listen_address(self.transport.as_str(), &self.endpoint, "gRPC")
205    }
206
207    /// Converts the connection settings into HTTP/2 server settings.
208    ///
209    /// The keepalive interval and timeout map across directly. The connection age limits and `max_concurrent_streams`
210    /// use a zero value to mean "no limit," which is translated here into the absence of a limit.
211    pub(crate) fn http2_config(&self) -> Http2Config {
212        let keepalive = &self.keepalive;
213        let mut config = Http2Config::default().with_keepalive(keepalive.time, keepalive.timeout);
214
215        if !keepalive.max_connection_age.is_zero() {
216            let grace = (!keepalive.max_connection_age_grace.is_zero()).then_some(keepalive.max_connection_age_grace);
217            config = config.with_max_connection_age(keepalive.max_connection_age, grace);
218        }
219
220        if self.max_concurrent_streams > 0 {
221            config = config.with_max_concurrent_streams(self.max_concurrent_streams);
222        }
223
224        config
225    }
226}
227
228impl OtlpHttpReceiver {
229    /// Returns the address the server listens on, or `None` if the endpoint is empty.
230    ///
231    /// # Errors
232    ///
233    /// If the transport and endpoint don't make a valid listen address, an error is returned.
234    pub fn listen_address(&self) -> Result<Option<ListenAddress>, GenericError> {
235        listen_address(&self.transport, &self.endpoint, "HTTP")
236    }
237}
238
239fn listen_address(transport: &str, endpoint: &str, protocol: &str) -> Result<Option<ListenAddress>, GenericError> {
240    if endpoint.is_empty() {
241        return Ok(None);
242    }
243
244    let address = format!("{transport}://{endpoint}");
245    ListenAddress::try_from(address.as_str())
246        .map(Some)
247        .map_err(|e| generic_error!("Invalid OTLP/{protocol} listen address `{address}`: {e}"))
248}
249
250/// Returns receiver settings with every server unset and no signal enabled.
251#[cfg(test)]
252pub(crate) fn receiver() -> OtlpReceiver {
253    let tls = OtlpReceiverTls {
254        cert_file: String::new(),
255        key_file: String::new(),
256        ca_file: String::new(),
257    };
258    OtlpReceiver {
259        grpc: OtlpGrpcReceiver {
260            endpoint: String::new(),
261            max_recv_msg_size_mib: 0,
262            transport: GrpcTransport::Tcp,
263            max_concurrent_streams: 0,
264            keepalive: OtlpKeepalive {
265                max_connection_age: Duration::ZERO,
266                max_connection_age_grace: Duration::ZERO,
267                time: Duration::ZERO,
268                timeout: Duration::ZERO,
269            },
270            tls: tls.clone(),
271        },
272        http: OtlpHttpReceiver {
273            endpoint: String::new(),
274            transport: "tcp".to_string(),
275            cors: CorsConfiguration::default(),
276            tls,
277            max_request_body_size: 0,
278        },
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use std::path::PathBuf;
285
286    use super::*;
287
288    fn tls(cert_file: &str, key_file: &str, ca_file: &str) -> OtlpReceiverTls {
289        OtlpReceiverTls {
290            cert_file: cert_file.to_string(),
291            key_file: key_file.to_string(),
292            ca_file: ca_file.to_string(),
293        }
294    }
295
296    #[test]
297    fn tls_is_enabled_by_a_certificate_and_key_with_an_optional_ca() {
298        assert!(tls("", "", "").build().expect("unset TLS is valid").is_none());
299
300        let config = tls("/cert.pem", "/key.pem", "")
301            .build()
302            .expect("a certificate and key are valid")
303            .expect("a certificate and key enable TLS");
304        assert_eq!(PathBuf::from("/cert.pem"), config.cert_file);
305        assert_eq!(PathBuf::from("/key.pem"), config.key_file);
306        assert_eq!(None, config.ca_file);
307
308        let config = tls("/cert.pem", "/key.pem", "/ca.pem")
309            .build()
310            .expect("a certificate, key, and CA are valid")
311            .expect("a certificate and key enable TLS");
312        assert_eq!(Some(PathBuf::from("/ca.pem")), config.ca_file);
313    }
314
315    #[test]
316    fn partial_tls_settings_are_rejected() {
317        for (cert_file, key_file, ca_file, expected) in [
318            ("", "", "/ca.pem", "`ca_file` is set"),
319            ("", "/key.pem", "", "`key_file` is set"),
320            ("", "/key.pem", "/ca.pem", "`key_file` is set"),
321            ("/cert.pem", "", "", "`cert_file` is set"),
322            ("/cert.pem", "", "/ca.pem", "`cert_file` is set"),
323        ] {
324            let error = tls(cert_file, key_file, ca_file)
325                .build()
326                .expect_err("partial TLS settings must not downgrade to plaintext");
327            assert!(
328                error.to_string().contains(expected),
329                "{cert_file:?} {key_file:?} {ca_file:?}: {error}"
330            );
331        }
332    }
333
334    #[test]
335    fn listen_addresses_combine_the_transport_and_endpoint() {
336        let mut receiver = receiver();
337        assert_eq!(receiver.grpc.listen_address().unwrap(), None);
338        assert_eq!(receiver.http.listen_address().unwrap(), None);
339
340        receiver.grpc.endpoint = "0.0.0.0:4317".to_string();
341        receiver.http.endpoint = "127.0.0.1:4318".to_string();
342        assert_eq!(
343            receiver.grpc.listen_address().unwrap().unwrap().to_string(),
344            "tcp://0.0.0.0:4317"
345        );
346        assert_eq!(
347            receiver.http.listen_address().unwrap().unwrap().to_string(),
348            "tcp://127.0.0.1:4318"
349        );
350
351        receiver.grpc.transport = GrpcTransport::Tcp;
352        receiver.grpc.endpoint = "not an address".to_string();
353        assert!(receiver.grpc.listen_address().is_err());
354    }
355
356    #[cfg(unix)]
357    #[test]
358    fn listen_addresses_combine_the_unix_transport_and_endpoint() {
359        let mut receiver = receiver();
360        receiver.grpc.transport = GrpcTransport::Unix;
361        receiver.grpc.endpoint = "/tmp/otlp-grpc.sock".to_string();
362        receiver.http.transport = "unix".to_string();
363        receiver.http.endpoint = "/tmp/otlp-http.sock".to_string();
364        assert_eq!(
365            receiver.grpc.listen_address().unwrap().unwrap().to_string(),
366            "unix:///tmp/otlp-grpc.sock"
367        );
368        assert_eq!(
369            receiver.http.listen_address().unwrap().unwrap().to_string(),
370            "unix:///tmp/otlp-http.sock"
371        );
372    }
373}