1#[cfg(test)]
2mod tests;
3
4use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
5use std::{fmt, str::FromStr};
6
7pub(crate) const MAX_KEY_BYTES: usize = 128;
8
9#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
22pub struct StableKey(String);
23
24impl StableKey {
25 pub fn parse(value: impl AsRef<str>) -> Result<Self, StableKeyError> {
30 let value = value.as_ref();
31 validate(value)?;
32
33 Ok(Self(value.to_string()))
34 }
35
36 #[must_use]
38 pub fn as_str(&self) -> &str {
39 &self.0
40 }
41
42 #[must_use]
44 pub fn into_string(self) -> String {
45 self.0
46 }
47}
48
49impl AsRef<str> for StableKey {
50 fn as_ref(&self) -> &str {
51 self.as_str()
52 }
53}
54
55impl<'de> Deserialize<'de> for StableKey {
56 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
57 #[derive(Deserialize)]
59 #[serde(rename = "StableKey")]
60 struct Text(String);
61
62 let Text(value) = Text::deserialize(deserializer)?;
63 validate(&value).map_err(D::Error::custom)?;
64
65 Ok(Self(value))
66 }
67}
68
69impl fmt::Display for StableKey {
70 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71 formatter.write_str(self.as_str())
72 }
73}
74
75impl FromStr for StableKey {
76 type Err = StableKeyError;
77
78 fn from_str(value: &str) -> Result<Self, Self::Err> {
79 Self::parse(value)
80 }
81}
82
83#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
89#[error("stable key '{stable_key}' is invalid: {reason}")]
90pub struct StableKeyError {
91 pub stable_key: String,
93 pub reason: &'static str,
95}
96
97pub fn validate(stable_key: &str) -> Result<(), StableKeyError> {
98 if stable_key.is_empty() {
99 return invalid(stable_key, "must not be empty");
100 }
101 if stable_key.len() > MAX_KEY_BYTES {
102 return invalid(stable_key, "must be at most 128 bytes");
103 }
104 if !stable_key.is_ascii() {
105 return invalid(stable_key, "must be ASCII");
106 }
107 if stable_key.bytes().any(|byte| byte.is_ascii_uppercase()) {
108 return invalid(stable_key, "must be lowercase");
109 }
110 if stable_key
111 .bytes()
112 .any(|byte| matches!(byte, b'\t'..=b'\r' | b' '))
113 {
114 return invalid(stable_key, "must not contain whitespace");
115 }
116 if stable_key.bytes().any(|byte| matches!(byte, b'/' | b'-')) {
117 return invalid(stable_key, "must not contain slashes or hyphens");
118 }
119 if stable_key.starts_with('.') || stable_key.ends_with('.') {
120 return invalid(stable_key, "must not start or end with a dot");
121 }
122
123 let Some(version_index) = stable_key
124 .as_bytes()
125 .windows(2)
126 .rposition(|pair| pair == b".v")
127 else {
128 return invalid(stable_key, "must end with .vN");
129 };
130 let version = &stable_key[version_index + 2..];
131 if version.is_empty()
132 || version.starts_with('0')
133 || !version.bytes().all(|byte| byte.is_ascii_digit())
134 {
135 return invalid(stable_key, "version suffix must be nonzero .vN");
136 }
137
138 let prefix = &stable_key[..version_index];
139 if prefix.is_empty() {
140 return invalid(
141 stable_key,
142 "must contain at least one segment before version",
143 );
144 }
145
146 for segment in prefix.as_bytes().split(|byte| *byte == b'.') {
147 if let Err(reason) = validate_segment(segment) {
148 return invalid(stable_key, reason);
149 }
150 }
151
152 Ok(())
153}
154
155pub fn is_key_prefix(value: &str) -> bool {
158 let Some(prefix) = value.strip_suffix('.') else {
159 return false;
160 };
161
162 value.len() <= MAX_KEY_BYTES - "v1".len()
163 && prefix
164 .as_bytes()
165 .split(|byte| *byte == b'.')
166 .all(|segment| validate_segment(segment).is_ok())
167}
168
169fn validate_segment(segment: &[u8]) -> Result<(), &'static str> {
170 let mut bytes = segment.iter().copied();
171 let Some(first) = bytes.next() else {
172 return Err("must not contain empty segments");
173 };
174 if !first.is_ascii_lowercase() {
175 return Err("segments must start with a lowercase letter");
176 }
177 if !bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') {
178 return Err("segments may contain only lowercase letters, digits, and underscores");
179 }
180
181 Ok(())
182}
183
184fn invalid<T>(stable_key: &str, reason: &'static str) -> Result<T, StableKeyError> {
185 Err(StableKeyError {
186 stable_key: stable_key.to_string(),
187 reason,
188 })
189}