Skip to main content

merry_core/
id.rs

1//! Validated identifier and name newtypes.
2
3use crate::CoreError;
4use schemars::JsonSchema;
5use serde::{Deserialize, Deserializer, Serialize, de};
6use std::{fmt, str::FromStr};
7use uuid::Uuid;
8
9const MAX_IDENTIFIER_LEN: usize = 128;
10const MAX_TOOL_NAME_LEN: usize = 64;
11const MAX_TOOL_CALL_ID_LEN: usize = 256;
12
13fn validate_common_identifier(
14    kind: &'static str,
15    value: &str,
16    max_len: usize,
17) -> Result<(), CoreError> {
18    if value.is_empty() {
19        return Err(invalid_identifier(kind, value, "must not be empty"));
20    }
21
22    if value.trim().is_empty() {
23        return Err(invalid_identifier(
24            kind,
25            value,
26            "must not be whitespace only",
27        ));
28    }
29
30    if value.trim() != value {
31        return Err(invalid_identifier(
32            kind,
33            value,
34            "must not have leading or trailing whitespace",
35        ));
36    }
37
38    if value.chars().count() > max_len {
39        return Err(invalid_identifier(
40            kind,
41            value,
42            "is longer than the allowed maximum length",
43        ));
44    }
45
46    if value.chars().any(char::is_control) {
47        return Err(invalid_identifier(
48            kind,
49            value,
50            "must not contain control characters",
51        ));
52    }
53
54    Ok(())
55}
56
57fn validate_session_id(kind: &'static str, value: &str, max_len: usize) -> Result<(), CoreError> {
58    validate_common_identifier(kind, value, max_len)?;
59
60    if value == "." || value == ".." {
61        return Err(invalid_identifier(kind, value, "must not be '.' or '..'"));
62    }
63
64    if !value
65        .bytes()
66        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
67    {
68        return Err(invalid_identifier(
69            kind,
70            value,
71            "must contain only ASCII letters, digits, '.', '_' or '-'",
72        ));
73    }
74
75    Ok(())
76}
77
78fn validate_tool_name(value: &str) -> Result<(), CoreError> {
79    validate_common_identifier("ToolName", value, MAX_TOOL_NAME_LEN)?;
80
81    let mut chars = value.chars();
82    let first = chars
83        .next()
84        .expect("common validation rejects empty values");
85    if !(first.is_ascii_alphabetic() || first == '_') {
86        return Err(invalid_identifier(
87            "ToolName",
88            value,
89            "must start with an ASCII letter or '_'",
90        ));
91    }
92
93    if !value
94        .bytes()
95        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
96    {
97        return Err(invalid_identifier(
98            "ToolName",
99            value,
100            "must contain only ASCII letters, digits, '_' or '-'",
101        ));
102    }
103
104    Ok(())
105}
106
107fn invalid_identifier(kind: &'static str, value: &str, reason: &'static str) -> CoreError {
108    CoreError::InvalidIdentifier {
109        kind,
110        value: value.to_owned(),
111        reason,
112    }
113}
114
115macro_rules! define_id {
116    ($type:ident, $kind:literal) => {
117        define_id!($type, $kind, MAX_IDENTIFIER_LEN, validate_common_identifier);
118    };
119    ($type:ident, $kind:literal, $max_len:expr) => {
120        define_id!($type, $kind, $max_len, validate_common_identifier);
121    };
122    ($type:ident, $kind:literal, $max_len:expr, $validator:path) => {
123        #[doc = concat!("Validated ", $kind, " newtype.")]
124        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema)]
125        #[serde(transparent)]
126        pub struct $type(String);
127
128        impl $type {
129            /// Creates a validated identifier from a borrowed string.
130            pub fn new(value: &str) -> Result<Self, CoreError> {
131                $validator($kind, value, $max_len)?;
132                Ok(Self(value.to_owned()))
133            }
134
135            /// Borrows the identifier as a string slice.
136            #[must_use]
137            pub fn as_str(&self) -> &str {
138                &self.0
139            }
140        }
141
142        impl fmt::Display for $type {
143            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
144                formatter.write_str(&self.0)
145            }
146        }
147
148        impl FromStr for $type {
149            type Err = CoreError;
150
151            fn from_str(value: &str) -> Result<Self, Self::Err> {
152                Self::new(value)
153            }
154        }
155
156        impl TryFrom<&str> for $type {
157            type Error = CoreError;
158
159            fn try_from(value: &str) -> Result<Self, Self::Error> {
160                Self::new(value)
161            }
162        }
163
164        impl TryFrom<String> for $type {
165            type Error = CoreError;
166
167            fn try_from(value: String) -> Result<Self, Self::Error> {
168                $validator($kind, &value, $max_len)?;
169                Ok(Self(value))
170            }
171        }
172
173        impl<'de> Deserialize<'de> for $type {
174            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
175            where
176                D: Deserializer<'de>,
177            {
178                let value = String::deserialize(deserializer)?;
179                Self::try_from(value).map_err(de::Error::custom)
180            }
181        }
182    };
183}
184
185define_id!(
186    SessionId,
187    "SessionId",
188    MAX_IDENTIFIER_LEN,
189    validate_session_id
190);
191define_id!(SkillId, "SkillId");
192define_id!(SubagentId, "SubagentId");
193define_id!(SubagentTaskId, "SubagentTaskId");
194define_id!(PlanId, "PlanId");
195define_id!(TrajectoryRecordId, "TrajectoryRecordId");
196define_id!(ProviderName, "ProviderName");
197define_id!(ToolAdapterId, "ToolAdapterId");
198define_id!(ToolSourceId, "ToolSourceId");
199define_id!(ToolBindingName, "ToolBindingName", 1024);
200define_id!(ToolSourceFingerprint, "ToolSourceFingerprint");
201define_id!(ToolCallBatchId, "ToolCallBatchId");
202define_id!(ToolCallId, "ToolCallId", MAX_TOOL_CALL_ID_LEN);
203
204impl SessionId {
205    /// Generates a random filesystem-safe session id.
206    #[must_use]
207    pub fn random() -> Self {
208        Self(Uuid::new_v4().to_string())
209    }
210}
211
212/// Provider-portable tool name.
213#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema)]
214#[serde(transparent)]
215pub struct ToolName(
216    #[schemars(
217        length(min = 1, max = 64),
218        regex(pattern = r"^[A-Za-z_][A-Za-z0-9_-]*$")
219    )]
220    String,
221);
222
223impl ToolName {
224    /// Creates a validated provider-portable tool name.
225    pub fn new(value: &str) -> Result<Self, CoreError> {
226        validate_tool_name(value)?;
227        Ok(Self(value.to_owned()))
228    }
229
230    /// Borrows the tool name as a string slice.
231    #[must_use]
232    pub fn as_str(&self) -> &str {
233        &self.0
234    }
235}
236
237impl fmt::Display for ToolName {
238    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
239        formatter.write_str(&self.0)
240    }
241}
242
243impl FromStr for ToolName {
244    type Err = CoreError;
245
246    fn from_str(value: &str) -> Result<Self, Self::Err> {
247        Self::new(value)
248    }
249}
250
251impl TryFrom<&str> for ToolName {
252    type Error = CoreError;
253
254    fn try_from(value: &str) -> Result<Self, Self::Error> {
255        Self::new(value)
256    }
257}
258
259impl TryFrom<String> for ToolName {
260    type Error = CoreError;
261
262    fn try_from(value: String) -> Result<Self, Self::Error> {
263        validate_tool_name(&value)?;
264        Ok(Self(value))
265    }
266}
267
268impl<'de> Deserialize<'de> for ToolName {
269    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
270    where
271        D: Deserializer<'de>,
272    {
273        let value = String::deserialize(deserializer)?;
274        Self::try_from(value).map_err(de::Error::custom)
275    }
276}