Skip to main content

artifactize_core/config/
identities.rs

1//! Declaration identifiers are validated once when configuration or saved profiles enter.
2
3use serde::{Deserialize, Serialize};
4use std::{borrow::Borrow, fmt, ops::Deref, str::FromStr};
5
6macro_rules! identity {
7    ($name:ident, $valid:expr) => {
8        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
9        #[serde(transparent)]
10        pub struct $name(String);
11        impl FromStr for $name {
12            type Err = String;
13            fn from_str(value: &str) -> Result<Self, Self::Err> {
14                if ($valid)(value) {
15                    Ok(Self(value.to_owned()))
16                } else {
17                    Err(format!("Invalid {}: {value:?}", stringify!($name)))
18                }
19            }
20        }
21        impl<'de> Deserialize<'de> for $name {
22            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
23                use serde::de::Error;
24                String::deserialize(deserializer)?
25                    .parse()
26                    .map_err(D::Error::custom)
27            }
28        }
29        impl $name {
30            pub fn as_str(&self) -> &str {
31                &self.0
32            }
33        }
34        impl Deref for $name {
35            type Target = str;
36            fn deref(&self) -> &str {
37                &self.0
38            }
39        }
40        impl AsRef<str> for $name {
41            fn as_ref(&self) -> &str {
42                &self.0
43            }
44        }
45        impl Borrow<str> for $name {
46            fn borrow(&self) -> &str {
47                &self.0
48            }
49        }
50        impl Borrow<String> for $name {
51            fn borrow(&self) -> &String {
52                &self.0
53            }
54        }
55        impl fmt::Display for $name {
56            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57                self.0.fmt(f)
58            }
59        }
60        impl PartialEq<str> for $name {
61            fn eq(&self, other: &str) -> bool {
62                self.0 == other
63            }
64        }
65        impl PartialEq<&str> for $name {
66            fn eq(&self, other: &&str) -> bool {
67                self.0 == *other
68            }
69        }
70        impl PartialEq<String> for $name {
71            fn eq(&self, other: &String) -> bool {
72                &self.0 == other
73            }
74        }
75        impl PartialEq<$name> for String {
76            fn eq(&self, other: &$name) -> bool {
77                *self == other.0
78            }
79        }
80        impl PartialEq<$name> for str {
81            fn eq(&self, other: &$name) -> bool {
82                self == other.0
83            }
84        }
85        impl PartialEq<$name> for &str {
86            fn eq(&self, other: &$name) -> bool {
87                *self == other.0
88            }
89        }
90    };
91}
92/// Two declaration identifiers of 64 bytes, joined by one underscore.
93const MAX_TOOL_NAME_BYTES: usize = 129;
94/// Endpoint namespaces retain a complete SHA-256 digest in lowercase hexadecimal.
95const ENDPOINT_HEX_BYTES: usize = 64;
96
97fn name(value: &str) -> bool {
98    super::identifier(value, "").is_ok()
99}
100identity!(ModelId, |value: &str| !value.trim().is_empty());
101identity!(ProfileVariantName, name);
102identity!(ToolOperationName, name);
103// Published tool names concatenate an operation and Artifact name with `_`; each
104// component is at most 64 ASCII bytes. Collision detection remains a registry concern.
105identity!(ToolName, |value: &str| !value.is_empty()
106    && value.len() <= MAX_TOOL_NAME_BYTES
107    && value.bytes().all(
108        |byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
109    ));
110// Provenance also names lifecycle commands; a dot cannot occur in published tools.
111identity!(ExecutionPinName, |value: &str| value
112    .strip_suffix(".start")
113    .or_else(|| value.strip_suffix(".stop"))
114    .unwrap_or(value)
115    .parse::<ToolName>()
116    .is_ok());
117identity!(EndpointId, |value: &str| value.len() == ENDPOINT_HEX_BYTES
118    && value.bytes().all(
119        |byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()
120    ));
121identity!(HubEpoch, |value: &str| !value.is_empty()
122    && value.len() <= crate::types::MAX_ID_BYTES
123    && value.bytes().all(
124        |byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
125    ));
126
127// An instruction or argv reference names an Artifact.
128identity!(ReferenceName, name);
129impl From<&crate::types::ArtifactName> for ReferenceName {
130    fn from(value: &crate::types::ArtifactName) -> Self {
131        // Artifact names and reference names have the same declaration grammar.
132        Self(value.to_string())
133    }
134}
135identity!(ChildPrefix, |value: &str| crate::config::validation::path(
136    value
137)
138.is_ok());
139identity!(LogicalPath, |value: &str| value == "."
140    || crate::config::validation::path(value).is_ok());
141
142impl AsRef<std::path::Path> for LogicalPath {
143    fn as_ref(&self) -> &std::path::Path {
144        std::path::Path::new(self.as_str())
145    }
146}
147
148impl AsRef<std::ffi::OsStr> for LogicalPath {
149    fn as_ref(&self) -> &std::ffi::OsStr {
150        std::ffi::OsStr::new(self.as_str())
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use serde_json::json;
158
159    #[test]
160    fn declaration_ids_validate_at_json_boundary_and_keep_string_forms() {
161        for invalid in ["", " ", "bad/name", "_bad", "a\nb"] {
162            assert!(serde_json::from_value::<ProfileVariantName>(json!(invalid)).is_err());
163            assert!(serde_json::from_value::<ToolOperationName>(json!(invalid)).is_err());
164        }
165        let model: ModelId = serde_json::from_value(json!("provider/model-v1")).unwrap();
166        assert_eq!(
167            serde_json::to_value(model).unwrap(),
168            json!("provider/model-v1")
169        );
170        for invalid in [
171            "",
172            "a/../b",
173            "a\\b",
174            &crate::test_os::windows_drive("outside"),
175        ] {
176            assert!(serde_json::from_value::<LogicalPath>(json!(invalid)).is_err());
177        }
178        for logical in [".", "folder/file.txt"] {
179            let path: LogicalPath = serde_json::from_value(json!(logical)).unwrap();
180            assert_eq!(serde_json::to_value(path).unwrap(), json!(logical));
181        }
182    }
183}