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
127identity!(MountAlias, name);
128// An instruction or argv reference can name either an Artifact or its owner's mount.
129identity!(ReferenceName, name);
130impl From<&crate::types::ArtifactName> for ReferenceName {
131    fn from(value: &crate::types::ArtifactName) -> Self {
132        // Artifact names and reference names have the same declaration grammar.
133        Self(value.to_string())
134    }
135}
136identity!(ChildPrefix, |value: &str| crate::config::validation::path(
137    value
138)
139.is_ok());
140identity!(LogicalPath, |value: &str| value == "."
141    || crate::config::validation::path(value).is_ok());
142
143impl AsRef<std::path::Path> for LogicalPath {
144    fn as_ref(&self) -> &std::path::Path {
145        std::path::Path::new(self.as_str())
146    }
147}
148
149impl AsRef<std::ffi::OsStr> for LogicalPath {
150    fn as_ref(&self) -> &std::ffi::OsStr {
151        std::ffi::OsStr::new(self.as_str())
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use serde_json::json;
159
160    #[test]
161    fn declaration_ids_validate_at_json_boundary_and_keep_string_forms() {
162        for invalid in ["", " ", "bad/name", "_bad", "a\nb"] {
163            assert!(serde_json::from_value::<ProfileVariantName>(json!(invalid)).is_err());
164            assert!(serde_json::from_value::<ToolOperationName>(json!(invalid)).is_err());
165        }
166        let model: ModelId = serde_json::from_value(json!("provider/model-v1")).unwrap();
167        assert_eq!(
168            serde_json::to_value(model).unwrap(),
169            json!("provider/model-v1")
170        );
171        for invalid in [
172            "",
173            "a/../b",
174            "a\\b",
175            &crate::test_os::windows_drive("outside"),
176        ] {
177            assert!(serde_json::from_value::<LogicalPath>(json!(invalid)).is_err());
178        }
179        for logical in [".", "folder/file.txt"] {
180            let path: LogicalPath = serde_json::from_value(json!(logical)).unwrap();
181            assert_eq!(serde_json::to_value(path).unwrap(), json!(logical));
182        }
183    }
184}