Skip to main content

ic_storage/key/
mod.rs

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///
10/// StableKey
11/// Canonical durable logical allocation identity.
12///
13/// A stable key names the logical store, not the current storage backend or
14/// allocation ID. Once committed, the key is permanently bound to its
15/// allocation; changing the key declares a new logical store.
16///
17/// Construction and deserialization enforce the same bounded canonical grammar.
18/// A checked key establishes identity syntax, not allocation or open authority.
19///
20
21#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
22pub struct StableKey(String);
23
24impl StableKey {
25    /// Parse and validate a canonical stable key string.
26    ///
27    /// Keys are bounded lowercase ASCII dot-separated names ending in a
28    /// nonzero `.vN` suffix.
29    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    /// Borrow the canonical stable-key string.
37    #[must_use]
38    pub fn as_str(&self) -> &str {
39        &self.0
40    }
41
42    /// Consume the key and return the canonical stable-key string.
43    #[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        // Retain the serialized newtype shape before checking its owned text.
58        #[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///
84/// StableKeyError
85/// Stable-key grammar validation failure.
86///
87
88#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
89#[error("stable key '{stable_key}' is invalid: {reason}")]
90pub struct StableKeyError {
91    /// Rejected stable-key string.
92    pub stable_key: String,
93    /// Stable-key grammar failure.
94    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
155// A namespace plus its synthetic `v1` suffix must fit the same key grammar.
156// Borrow the prefix rather than allocating a temporary key just to discard it.
157pub 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}