Skip to main content

gcloud_observability/otlp/
endpoint.rs

1use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
2use gcloud_sdk::tonic::codegen::http::uri::{Scheme, Uri};
3use serde::{Deserialize, Serialize, Serializer};
4use std::fmt::{Display, Formatter};
5use std::str::FromStr;
6
7/// The `https` URI the OTLP exporters send to, such as the Telemetry API's global
8/// `https://telemetry.googleapis.com` or a regional `https://telemetry.REGION.rep.googleapis.com`
9/// (<https://docs.cloud.google.com/stackdriver/docs/reference/telemetry/overview>).
10///
11/// Plain `http` is refused, because every request carries the credentials' access token.
12///
13/// ```
14/// use gcloud_observability::otlp::TelemetryEndpoint;
15///
16/// let regional: TelemetryEndpoint = "https://telemetry.europe-west1.rep.googleapis.com".parse()?;
17/// assert!("http://telemetry.googleapis.com".parse::<TelemetryEndpoint>().is_err());
18/// # Ok::<(), gcloud_observability::errors::GcloudObservabilityError>(())
19/// ```
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
21#[serde(try_from = "String")]
22pub struct TelemetryEndpoint(String);
23
24impl TelemetryEndpoint {
25    /// # Errors
26    ///
27    /// [`GcloudObservabilityError::InvalidParametersError`] for the field `endpoint` when
28    /// `endpoint` is not a URI, or is not `https`, or has no host.
29    pub fn new(endpoint: impl Into<String>) -> GcloudObservabilityResult<Self> {
30        let endpoint = endpoint.into();
31        let uri = endpoint.parse::<Uri>().map_err(|error| {
32            GcloudObservabilityError::invalid_parameters(
33                "endpoint",
34                format!("is not a URI ({error}), got {endpoint:?}"),
35            )
36        })?;
37        if uri.scheme() != Some(&Scheme::HTTPS) || uri.host().is_none_or(str::is_empty) {
38            return Err(GcloudObservabilityError::invalid_parameters(
39                "endpoint",
40                format!("must be an https URI with a host, got {endpoint:?}"),
41            ));
42        }
43        Ok(Self(endpoint))
44    }
45}
46
47impl Display for TelemetryEndpoint {
48    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49        Display::fmt(&self.0, f)
50    }
51}
52
53impl FromStr for TelemetryEndpoint {
54    type Err = GcloudObservabilityError;
55
56    fn from_str(endpoint: &str) -> Result<Self, Self::Err> {
57        Self::new(endpoint)
58    }
59}
60
61impl TryFrom<String> for TelemetryEndpoint {
62    type Error = GcloudObservabilityError;
63
64    fn try_from(endpoint: String) -> Result<Self, Self::Error> {
65        Self::new(endpoint)
66    }
67}
68
69impl Serialize for TelemetryEndpoint {
70    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
71        serializer.serialize_str(&self.0)
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn endpoint_is_an_https_uri_with_a_host() {
81        for accepted in [
82            "https://telemetry.googleapis.com",
83            "https://telemetry.europe-west1.rep.googleapis.com",
84            "https://collector.internal:4317",
85        ] {
86            assert!(
87                TelemetryEndpoint::new(accepted).is_ok(),
88                "{accepted:?} is an endpoint"
89            );
90        }
91
92        for refused in [
93            "",
94            "not a uri",
95            "telemetry.googleapis.com",
96            "http://telemetry.googleapis.com",
97            "https://",
98            "https://:4317",
99        ] {
100            assert!(
101                matches!(
102                    TelemetryEndpoint::new(refused),
103                    Err(GcloudObservabilityError::InvalidParametersError(ref error))
104                        if error.field == "endpoint"
105                ),
106                "{refused:?} is not an endpoint"
107            );
108        }
109    }
110
111    #[test]
112    fn endpoint_is_checked_on_every_way_in() {
113        let global = TelemetryEndpoint::new("https://telemetry.googleapis.com").unwrap();
114
115        assert_eq!(
116            "https://telemetry.googleapis.com"
117                .parse::<TelemetryEndpoint>()
118                .unwrap(),
119            global
120        );
121        assert!("http://telemetry.googleapis.com"
122            .parse::<TelemetryEndpoint>()
123            .is_err());
124        assert!(
125            TelemetryEndpoint::try_from("http://telemetry.googleapis.com".to_string()).is_err()
126        );
127        assert!(
128            serde_json::from_str::<TelemetryEndpoint>(r#""http://telemetry.googleapis.com""#)
129                .is_err()
130        );
131
132        let json = serde_json::to_string(&global).unwrap();
133        assert_eq!(json, r#""https://telemetry.googleapis.com""#);
134        assert_eq!(
135            serde_json::from_str::<TelemetryEndpoint>(&json).unwrap(),
136            global
137        );
138    }
139}