Skip to main content

objectstore_types/
usecase.rs

1//! Validated usecase names shared by clients and the server.
2
3use std::borrow::Borrow;
4use std::cmp::Ordering;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::str::FromStr;
8use std::sync::Arc;
9
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12/// Minimum length of a usecase name in bytes.
13pub const MIN_USECASE_NAME_LENGTH: usize = 3;
14
15/// Maximum length of a usecase name in bytes.
16pub const MAX_USECASE_NAME_LENGTH: usize = 64;
17
18/// Message for [`InvalidUsecaseName::InvalidLength`].
19const INVALID_LENGTH: &str = "invalid usecase name: must be 3-64 ASCII characters long";
20
21/// Message for [`InvalidUsecaseName::InvalidChar`], without the position.
22const INVALID_CHAR: &str = "invalid usecase name: expected ASCII letters, digits, '_' or '-'";
23
24/// Storage for a validated [`Usecase`] name.
25#[derive(Clone)]
26enum Repr {
27    /// A name validated by [`Usecase::from_static`], stored without allocating.
28    Static(&'static str),
29    /// A name validated at runtime by [`Usecase::new`].
30    Dynamic(Arc<str>),
31}
32
33/// A validated, case-sensitive name for an Objectstore workload.
34///
35/// Names must be 3–64 ASCII characters from `[A-Za-z0-9_-]`. Any permitted
36/// character may appear in any position, including names consisting entirely of
37/// underscores or hyphens. Names are never normalized.
38///
39/// Construction and deserialization both validate the name. The contents cannot
40/// be mutated after construction.
41///
42/// ```
43/// use objectstore_types::usecase::Usecase;
44///
45/// let name = Usecase::new("debug-files")?;
46/// assert_eq!(name.as_str(), "debug-files");
47/// assert!(Usecase::new("testing/org=999/injected").is_err());
48/// # Ok::<(), objectstore_types::usecase::InvalidUsecaseName>(())
49/// ```
50///
51/// Use [`Usecase::from_static`] for statically known names and [`Usecase::new`]
52/// for dynamic names.
53#[derive(Clone)]
54pub struct Usecase(Repr);
55
56impl Usecase {
57    /// Creates a validated usecase name from a borrowed or owned string.
58    ///
59    /// Use [`Self::from_static`] for statically defined names.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`InvalidUsecaseName`] if the name violates the rules on
64    /// [`Usecase`].
65    pub fn new(name: impl AsRef<str>) -> Result<Self, InvalidUsecaseName> {
66        let name = name.as_ref();
67        validate(name)?;
68        Ok(Self(Repr::Dynamic(name.into())))
69    }
70
71    /// Creates a usecase name from a name known at compile time.
72    ///
73    /// Use [`Self::new`] for dynamic names. The name is stored without
74    /// allocating, so the result can initialize a `static`:
75    ///
76    /// ```
77    /// use objectstore_types::usecase::Usecase;
78    ///
79    /// static ATTACHMENTS: Usecase = Usecase::from_static("attachments");
80    /// assert_eq!(ATTACHMENTS.as_str(), "attachments");
81    /// ```
82    ///
83    /// # Panics
84    ///
85    /// Panics if the name violates the rules on [`Usecase`]. In a const
86    /// context, this panic is reported as a compile error:
87    ///
88    /// ```compile_fail
89    /// use objectstore_types::usecase::Usecase;
90    ///
91    /// static BROKEN: Usecase = Usecase::from_static("attachments/v2");
92    /// ```
93    #[track_caller]
94    pub const fn from_static(name: &'static str) -> Self {
95        match validate(name) {
96            Ok(()) => Self(Repr::Static(name)),
97            // Const panics only accept a single `&str`, so the position is omitted.
98            Err(InvalidUsecaseName::InvalidLength) => panic!("{}", INVALID_LENGTH),
99            Err(InvalidUsecaseName::InvalidChar(_)) => panic!("{}", INVALID_CHAR),
100        }
101    }
102
103    /// Returns the usecase name as a string slice.
104    pub fn as_str(&self) -> &str {
105        match &self.0 {
106            Repr::Static(name) => name,
107            Repr::Dynamic(name) => name,
108        }
109    }
110}
111
112impl fmt::Debug for Usecase {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.debug_tuple("Usecase").field(&self.as_str()).finish()
115    }
116}
117
118impl PartialEq for Usecase {
119    fn eq(&self, other: &Self) -> bool {
120        self.as_str() == other.as_str()
121    }
122}
123
124impl Eq for Usecase {}
125
126impl PartialOrd for Usecase {
127    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
128        Some(self.cmp(other))
129    }
130}
131
132impl Ord for Usecase {
133    fn cmp(&self, other: &Self) -> Ordering {
134        self.as_str().cmp(other.as_str())
135    }
136}
137
138impl Hash for Usecase {
139    fn hash<H: Hasher>(&self, state: &mut H) {
140        self.as_str().hash(state);
141    }
142}
143
144impl AsRef<str> for Usecase {
145    fn as_ref(&self) -> &str {
146        self.as_str()
147    }
148}
149
150impl Borrow<str> for Usecase {
151    fn borrow(&self) -> &str {
152        self.as_str()
153    }
154}
155
156impl fmt::Display for Usecase {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.write_str(self.as_str())
159    }
160}
161
162impl FromStr for Usecase {
163    type Err = InvalidUsecaseName;
164
165    fn from_str(name: &str) -> Result<Self, Self::Err> {
166        Self::new(name)
167    }
168}
169
170impl TryFrom<&str> for Usecase {
171    type Error = InvalidUsecaseName;
172
173    fn try_from(name: &str) -> Result<Self, Self::Error> {
174        Self::new(name)
175    }
176}
177
178impl TryFrom<String> for Usecase {
179    type Error = InvalidUsecaseName;
180
181    fn try_from(name: String) -> Result<Self, Self::Error> {
182        Self::new(name)
183    }
184}
185
186impl From<Usecase> for String {
187    fn from(name: Usecase) -> Self {
188        name.as_str().to_owned()
189    }
190}
191
192impl Serialize for Usecase {
193    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
194    where
195        S: Serializer,
196    {
197        serializer.serialize_str(self.as_str())
198    }
199}
200
201impl<'de> Deserialize<'de> for Usecase {
202    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
203    where
204        D: Deserializer<'de>,
205    {
206        deserializer.deserialize_str(UsecaseVisitor)
207    }
208}
209
210/// An error indicating that a usecase name is invalid.
211#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
212pub enum InvalidUsecaseName {
213    /// The name is outside the permitted length range.
214    #[error("{message}", message = INVALID_LENGTH)]
215    InvalidLength,
216    /// The name contains a character outside the permitted set, starting at
217    /// this byte position.
218    #[error("{message}, at position {0}", message = INVALID_CHAR)]
219    InvalidChar(usize),
220}
221
222/// Checks whether a name follows the rules on [`Usecase`].
223const fn validate(name: &str) -> Result<(), InvalidUsecaseName> {
224    let bytes = name.as_bytes();
225    if bytes.len() < MIN_USECASE_NAME_LENGTH || bytes.len() > MAX_USECASE_NAME_LENGTH {
226        return Err(InvalidUsecaseName::InvalidLength);
227    }
228    let mut i = 0;
229    while i < bytes.len() {
230        let b = bytes[i];
231        if !b.is_ascii_alphanumeric() && b != b'_' && b != b'-' {
232            return Err(InvalidUsecaseName::InvalidChar(i));
233        }
234        i += 1;
235    }
236    Ok(())
237}
238
239/// Deserializes a [`Usecase`] from a string or UTF-8 bytes.
240struct UsecaseVisitor;
241
242impl serde::de::Visitor<'_> for UsecaseVisitor {
243    type Value = Usecase;
244
245    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        f.write_str("a usecase name")
247    }
248
249    fn visit_str<E>(self, name: &str) -> Result<Self::Value, E>
250    where
251        E: serde::de::Error,
252    {
253        Usecase::new(name).map_err(E::custom)
254    }
255
256    fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
257    where
258        E: serde::de::Error,
259    {
260        let name = std::str::from_utf8(bytes)
261            .map_err(|_| E::invalid_value(serde::de::Unexpected::Bytes(bytes), &self))?;
262        self.visit_str(name)
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn validates_names() {
272        for name in [
273            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-",
274            "___",
275        ] {
276            assert_eq!(Usecase::new(name).unwrap().as_str(), name);
277        }
278        for name in ["", "_", "ab", &"a".repeat(65)] {
279            assert_eq!(Usecase::new(name), Err(InvalidUsecaseName::InvalidLength));
280        }
281        for (name, position) in [
282            ("testing/org=999/injected", 7),
283            ("test.name", 4),
284            ("test name", 4),
285            ("café", 3),
286            ("ab€cd", 2),
287            ("ab🦀cd", 2),
288        ] {
289            assert_eq!(
290                Usecase::new(name),
291                Err(InvalidUsecaseName::InvalidChar(position))
292            );
293        }
294        assert_eq!(
295            InvalidUsecaseName::InvalidChar(7).to_string(),
296            "invalid usecase name: expected ASCII letters, digits, '_' or '-', at position 7"
297        );
298    }
299
300    #[test]
301    fn from_static_validates_in_const_context() {
302        const NAME: Usecase = Usecase::from_static("debug-files");
303        assert_eq!(NAME.as_str(), "debug-files");
304    }
305
306    #[test]
307    #[should_panic(expected = "invalid usecase name")]
308    fn from_static_panics_on_invalid_name() {
309        Usecase::from_static("testing/org=999/injected");
310    }
311
312    #[test]
313    fn static_and_dynamic_names_are_equal() {
314        use std::collections::HashSet;
315
316        let dynamic = Usecase::new("debug-files").unwrap();
317        let static_ = Usecase::from_static("debug-files");
318        assert_eq!(dynamic, static_);
319        assert_eq!(dynamic.cmp(&static_), Ordering::Equal);
320        assert_eq!(format!("{dynamic:?}"), r#"Usecase("debug-files")"#);
321        assert_eq!(format!("{static_:?}"), r#"Usecase("debug-files")"#);
322        let set = HashSet::from([dynamic]);
323        assert!(set.contains(&static_));
324        assert!(set.contains("debug-files"));
325    }
326
327    #[test]
328    fn serde_validates_and_uses_strings() {
329        let name = Usecase::new("Debug_Files-123").unwrap();
330        let serialized = serde_json::to_string(&name).unwrap();
331        assert_eq!(serialized, r#""Debug_Files-123""#);
332        assert_eq!(serde_json::from_str::<Usecase>(&serialized).unwrap(), name);
333        // Escapes can't be borrowed from the input, so this takes the transient path.
334        let escaped = r#""Debug\u005fFiles-123""#;
335        assert_eq!(serde_json::from_str::<Usecase>(escaped).unwrap(), name);
336        assert!(serde_json::from_str::<Usecase>(r#""_""#).is_err());
337    }
338
339    #[test]
340    fn string_conversions_preserve_names() {
341        let input = "Debug_Files-123";
342        let name: Usecase = input.parse().unwrap();
343        assert_eq!(name.as_ref(), input);
344        assert_eq!(name.to_string(), input);
345        let owned = String::from(name);
346        assert_eq!(Usecase::try_from(owned).unwrap().as_str(), input);
347    }
348}