Skip to main content

gcloud_observability/
ids.rs

1//! The validated identifier the Cloud Logging API and OTLP log sinks take: the log the entries go
2//! to.
3//!
4//! It is checked once, where the value enters, so that a malformed one fails at startup with
5//! [`GcloudObservabilityError::InvalidParametersError`]. Used unchecked, it would surface only
6//! as failed exports in a background task.
7
8use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
9use serde::{Deserialize, Serialize, Serializer};
10use std::borrow::Cow;
11use std::fmt::{Display, Formatter};
12use std::str::FromStr;
13
14const LOG_ID_RULE: &str = "must be 1 to 511 letters, digits and any of / _ - .";
15
16/// The ID of the Cloud Logging log entries are written to, such as `orders` or
17/// `orders/checkout`: 1 to 511 letters, digits, `/`, `_`, `-` and `.`.
18///
19/// ```
20/// use gcloud_observability::ids::LogId;
21///
22/// const CHECKOUT: LogId = LogId::from_static("orders/checkout");
23///
24/// let configured: LogId = "orders/checkout".parse()?;
25/// assert_eq!(configured, CHECKOUT);
26/// assert!("orders checkout".parse::<LogId>().is_err());
27/// # Ok::<(), gcloud_observability::errors::GcloudObservabilityError>(())
28/// ```
29#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
30#[serde(try_from = "String")]
31pub struct LogId(Cow<'static, str>);
32
33impl LogId {
34    /// # Errors
35    ///
36    /// [`GcloudObservabilityError::InvalidParametersError`] for the field `log_id` when `id`
37    /// breaks the rules in the [type docs](Self).
38    pub fn new(id: impl Into<String>) -> GcloudObservabilityResult<Self> {
39        let id = id.into();
40        if is_log_id(&id) {
41            Ok(Self(Cow::Owned(id)))
42        } else {
43            Err(GcloudObservabilityError::invalid_parameters(
44                "log_id",
45                format!("{LOG_ID_RULE}, got {id:?}"),
46            ))
47        }
48    }
49
50    /// Checks `id` at compile time when used in a `const`, where an invalid one fails the
51    /// build.
52    ///
53    /// # Panics
54    ///
55    /// When called at run time with an `id` that [`Self::new`] refuses.
56    pub const fn from_static(id: &'static str) -> Self {
57        if !is_log_id(id) {
58            panic!("{}", LOG_ID_RULE);
59        }
60        Self(Cow::Borrowed(id))
61    }
62}
63
64impl Display for LogId {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        Display::fmt(&*self.0, f)
67    }
68}
69
70impl FromStr for LogId {
71    type Err = GcloudObservabilityError;
72
73    fn from_str(id: &str) -> Result<Self, Self::Err> {
74        Self::new(id)
75    }
76}
77
78impl TryFrom<String> for LogId {
79    type Error = GcloudObservabilityError;
80
81    fn try_from(id: String) -> Result<Self, Self::Error> {
82        Self::new(id)
83    }
84}
85
86impl Serialize for LogId {
87    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
88        serializer.serialize_str(&self.0)
89    }
90}
91
92// Cloud Logging's rule for `[LOG_ID]` in `logName`, which "must be less than 512 characters
93// long": https://docs.cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
94const fn is_log_id(id: &str) -> bool {
95    const LOG_ID_CHARACTERS: &[u8] =
96        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/_-.";
97    !id.is_empty() && id.len() < 512 && consists_of(id.as_bytes(), LOG_ID_CHARACTERS)
98}
99
100// The slice methods that would do the next two are not `const`, and `from_static` checks at
101// compile time.
102
103const fn consists_of(bytes: &[u8], allowed: &[u8]) -> bool {
104    let mut rest = bytes;
105    while let [byte, tail @ ..] = rest {
106        if position_of(*byte, allowed).is_none() {
107            return false;
108        }
109        rest = tail;
110    }
111    true
112}
113
114const fn position_of(byte: u8, bytes: &[u8]) -> Option<usize> {
115    let mut index = 0;
116    while index < bytes.len() {
117        if bytes[index] == byte {
118            return Some(index);
119        }
120        index += 1;
121    }
122    None
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn refused_field<T: std::fmt::Debug>(result: GcloudObservabilityResult<T>) -> String {
130        match result {
131            Err(GcloudObservabilityError::InvalidParametersError(error)) => error.field,
132            other => panic!("expected an InvalidParametersError, got {other:?}"),
133        }
134    }
135
136    #[test]
137    fn log_id_follows_cloud_loggings_naming_rules() {
138        let longest = "a".repeat(511);
139        for accepted in ["o", "Orders/check-out_v1.2", longest.as_str()] {
140            assert!(LogId::new(accepted).is_ok(), "{accepted:?} is a log ID");
141        }
142
143        let too_long = "a".repeat(512);
144        for refused in [
145            "",
146            too_long.as_str(),
147            "orders log",
148            "orders:log",
149            "orders%2Flog",
150        ] {
151            assert_eq!(
152                refused_field(LogId::new(refused)),
153                "log_id",
154                "{refused:?} is not a log ID"
155            );
156        }
157    }
158
159    #[test]
160    fn log_id_is_checked_on_every_way_in() {
161        let checkout = LogId::from_static("orders/checkout");
162
163        assert_eq!("orders/checkout".parse::<LogId>().unwrap(), checkout);
164        assert_eq!(
165            LogId::try_from("orders/checkout".to_string()).unwrap(),
166            checkout
167        );
168        assert!("orders checkout".parse::<LogId>().is_err());
169        assert!(LogId::try_from("orders checkout".to_string()).is_err());
170        assert!(serde_json::from_str::<LogId>(r#""orders checkout""#).is_err());
171
172        let json = serde_json::to_string(&checkout).unwrap();
173        assert_eq!(json, r#""orders/checkout""#);
174        assert_eq!(serde_json::from_str::<LogId>(&json).unwrap(), checkout);
175    }
176}