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/// A provider-safe tool name: a tool's FQN and its Artifact's name joined by `_`.
93const MAX_TOOL_NAME_BYTES: usize = MAX_TOOL_FQN_BYTES + 1 + 64;
94/// A tool's dotted name: a few namespace segments and the tool's own identifier.
95const MAX_TOOL_FQN_BYTES: usize = 128;
96/// Endpoint namespaces retain a complete SHA-256 digest in lowercase hexadecimal.
97const ENDPOINT_HEX_BYTES: usize = 64;
98
99fn name(value: &str) -> bool {
100    super::identifier(value, "").is_ok()
101}
102pub use artifactize_provider::names::ModelId;
103identity!(ProfileName, name);
104identity!(ToolFqn, |value: &str| ToolFqn::namespace(value).is_ok());
105// Published tool names concatenate an operation and Artifact name with `_`; each
106// component is at most 64 ASCII bytes. Collision detection remains a registry concern.
107identity!(ToolName, |value: &str| !value.is_empty()
108    && value.len() <= MAX_TOOL_NAME_BYTES
109    && value.bytes().all(
110        |byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
111    ));
112// Provenance also names session lifecycle commands after a `:`, which no published tool name
113// or tool FQN contains, so `svc.start` and a session's start never share a pin.
114identity!(ExecutionPinName, |value: &str| value
115    .strip_suffix(":start")
116    .or_else(|| value.strip_suffix(":stop"))
117    .unwrap_or(value)
118    .parse::<ToolName>()
119    .is_ok());
120identity!(EndpointId, |value: &str| value.len() == ENDPOINT_HEX_BYTES
121    && value.bytes().all(
122        |byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()
123    ));
124identity!(HubEpoch, |value: &str| !value.is_empty()
125    && value.len() <= crate::types::MAX_ID_BYTES
126    && value.bytes().all(
127        |byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
128    ));
129
130// An instruction or argv reference names an Artifact.
131identity!(ReferenceName, |value: &str| super::artifact_name(value, "")
132    .is_ok());
133impl From<&crate::types::ArtifactName> for ReferenceName {
134    fn from(value: &crate::types::ArtifactName) -> Self {
135        // Artifact names and reference names have the same declaration grammar.
136        Self(value.to_string())
137    }
138}
139identity!(ChildPrefix, |value: &str| crate::config::validation::path(
140    value
141)
142.is_ok());
143pub use artifactize_tools::scope::LogicalPath;
144
145#[cfg(test)]
146mod tests;
147
148/// Match other declaration keys so plugin type names remain short and portable.
149const MAX_ARTIFACT_TYPE_BYTES: usize = 64;
150
151identity!(PluginName, |value: &str| {
152    value.len() <= MAX_ARTIFACT_TYPE_BYTES
153        && value
154            .bytes()
155            .next()
156            .is_some_and(|byte| byte.is_ascii_lowercase())
157        && value
158            .bytes()
159            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
160        && crate::platform::paths::portable_component(std::ffi::OsStr::new(value)).is_ok()
161});
162
163impl ToolFqn {
164    /// `a.b.c`: dot-separated identifiers, each starting with a letter.
165    pub fn namespace(value: &str) -> Result<(), String> {
166        if value.is_empty() || value.len() > MAX_TOOL_FQN_BYTES {
167            return Err(format!(
168                "A tool name is 1–{MAX_TOOL_FQN_BYTES} bytes: {value:?}."
169            ));
170        }
171        for segment in value.split('.') {
172            if !segment
173                .as_bytes()
174                .first()
175                .is_some_and(u8::is_ascii_alphabetic)
176            {
177                return Err(format!(
178                    "Each part of a tool name starts with a letter: {value:?}."
179                ));
180            }
181            super::identifier(segment, "A tool name's part")?;
182        }
183        Ok(())
184    }
185
186    /// The namespace of `ns.tool`: everything before its last dot.
187    pub fn namespace_part(&self) -> &str {
188        self.0
189            .rsplit_once('.')
190            .map_or("", |(namespace, _)| namespace)
191    }
192
193    /// The name a provider sees: `{fqn with . as _}_{artifact}`. Registries reject two tools
194    /// whose names meet here.
195    pub fn published(&self, artifact: &str) -> ToolName {
196        format!("{}_{artifact}", self.0.replace('.', "_"))
197            .parse()
198            .expect("a validated FQN and Artifact name form a provider-safe tool name")
199    }
200}