Skip to main content

libtea_core/
ids.rs

1//! Identifier newtypes.
2//!
3//! A TEA UUID is unique only together with an API base and an object type.
4//! These newtypes stop product, release, component, collection, and artifact
5//! identifiers from being interchangeable in the type system.
6
7use std::fmt;
8
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10use uuid::Uuid;
11
12use crate::error::ModelError;
13
14/// Lowercase RFC 9562 hyphenated UUID, matching the TEA `uuid` schema.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct TeaUuid(Uuid);
17
18impl TeaUuid {
19    /// Parse the canonical lowercase hyphenated form.
20    ///
21    /// # Errors
22    ///
23    /// Returns an error when the text is not a lowercase hyphenated UUID.
24    pub fn parse(text: &str) -> Result<Self, ModelError> {
25        if text.len() != 36 || text.chars().any(|c| c.is_ascii_uppercase()) {
26            return Err(ModelError::Invalid(
27                "UUID must be 36 lowercase hexadecimal characters with hyphens".into(),
28            ));
29        }
30        let parsed = Uuid::parse_str(text)
31            .map_err(|err| ModelError::Invalid(format!("UUID is not valid: {err}")))?;
32        if parsed.as_hyphenated().to_string() != text {
33            return Err(ModelError::Invalid(
34                "UUID must use the hyphenated textual form".into(),
35            ));
36        }
37        Ok(Self(parsed))
38    }
39
40    /// Borrow the underlying UUID.
41    #[must_use]
42    pub fn as_uuid(&self) -> &Uuid {
43        &self.0
44    }
45}
46
47impl fmt::Display for TeaUuid {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(f, "{}", self.0.as_hyphenated())
50    }
51}
52
53impl Serialize for TeaUuid {
54    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
55        serializer.serialize_str(&self.to_string())
56    }
57}
58
59impl<'de> Deserialize<'de> for TeaUuid {
60    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
61        let text = String::deserialize(deserializer)?;
62        Self::parse(&text).map_err(serde::de::Error::custom)
63    }
64}
65
66macro_rules! id_newtype {
67    ($name:ident, $doc:literal) => {
68        #[doc = $doc]
69        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
70        #[serde(transparent)]
71        pub struct $name(TeaUuid);
72
73        impl $name {
74            /// Parse a canonical TEA UUID.
75            ///
76            /// # Errors
77            ///
78            /// Returns an error when `text` is not a canonical TEA UUID.
79            pub fn parse(text: &str) -> Result<Self, ModelError> {
80                Ok(Self(TeaUuid::parse(text)?))
81            }
82
83            /// Wrap an already validated UUID.
84            #[must_use]
85            pub fn from_tea_uuid(uuid: TeaUuid) -> Self {
86                Self(uuid)
87            }
88
89            /// Borrow the inner UUID.
90            #[must_use]
91            pub fn as_tea_uuid(&self) -> &TeaUuid {
92                &self.0
93            }
94        }
95
96        impl fmt::Display for $name {
97            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98                self.0.fmt(f)
99            }
100        }
101    };
102}
103
104id_newtype!(ProductId, "UUID of a TEA Product at one API base.");
105id_newtype!(
106    ProductReleaseId,
107    "UUID of a TEA Product Release at one API base."
108);
109id_newtype!(ComponentId, "UUID of a TEA Component at one API base.");
110id_newtype!(
111    ComponentReleaseId,
112    "UUID of a TEA Component Release at one API base."
113);
114id_newtype!(
115    CollectionId,
116    "UUID of a TEA Collection. The specification requires this to equal the parent release UUID."
117);
118id_newtype!(ArtifactId, "UUID of a TEA Artifact at one API base.");
119id_newtype!(DistributionId, "UUID of a component-release distribution.");
120
121impl CollectionId {
122    /// Collection UUID taken from its parent product release.
123    #[must_use]
124    pub fn from_product_release(id: ProductReleaseId) -> Self {
125        Self(*id.as_tea_uuid())
126    }
127
128    /// Collection UUID taken from its parent component release.
129    #[must_use]
130    pub fn from_component_release(id: ComponentReleaseId) -> Self {
131        Self(*id.as_tea_uuid())
132    }
133}
134
135/// RFC 3339 UTC timestamp with a `Z` designator, as required by the `date-time` schema.
136#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
137#[serde(try_from = "String", into = "String")]
138pub struct TeaTimestamp(String);
139
140impl TeaTimestamp {
141    /// Validate a TEA timestamp.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error when the text does not match the normative pattern.
146    pub fn parse(text: &str) -> Result<Self, ModelError> {
147        if !is_tea_timestamp(text) {
148            return Err(ModelError::Invalid(format!(
149                "timestamp must be RFC 3339 UTC with a Z designator, got `{text}`"
150            )));
151        }
152        Ok(Self(text.to_owned()))
153    }
154
155    /// Borrow the original timestamp text.
156    #[must_use]
157    pub fn as_str(&self) -> &str {
158        &self.0
159    }
160}
161
162impl TryFrom<String> for TeaTimestamp {
163    type Error = ModelError;
164
165    fn try_from(value: String) -> Result<Self, Self::Error> {
166        Self::parse(&value)
167    }
168}
169
170impl From<TeaTimestamp> for String {
171    fn from(value: TeaTimestamp) -> Self {
172        value.0
173    }
174}
175
176impl fmt::Display for TeaTimestamp {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.write_str(&self.0)
179    }
180}
181
182fn is_tea_timestamp(text: &str) -> bool {
183    let bytes = text.as_bytes();
184    if bytes.len() < 20 || bytes[10] != b'T' || *bytes.last().unwrap_or(&0) != b'Z' {
185        return false;
186    }
187    let (date, rest) = text.split_at(10);
188    let time_and_frac = &rest[1..rest.len() - 1];
189    let (time, frac) = match time_and_frac.split_once('.') {
190        Some((time, frac)) => (time, Some(frac)),
191        None => (time_and_frac, None),
192    };
193    if date.len() != 10 || time.len() != 8 {
194        return false;
195    }
196    let date_ok = date.as_bytes()[4] == b'-'
197        && date.as_bytes()[7] == b'-'
198        && date
199            .as_bytes()
200            .iter()
201            .enumerate()
202            .all(|(i, b)| i == 4 || i == 7 || b.is_ascii_digit());
203    let time_ok = time.as_bytes()[2] == b':'
204        && time.as_bytes()[5] == b':'
205        && time
206            .as_bytes()
207            .iter()
208            .enumerate()
209            .all(|(i, b)| i == 2 || i == 5 || b.is_ascii_digit());
210    let frac_ok = frac
211        .map(|f| !f.is_empty() && f.bytes().all(|b| b.is_ascii_digit()))
212        .unwrap_or(true);
213    date_ok && time_ok && frac_ok
214}