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/// Canonical durable logical allocation identity.
10///
11/// A stable key names the logical store, not the current storage backend or
12/// allocation ID. Once committed, the key is permanently bound to its
13/// allocation; changing the key declares a new logical store.
14///
15/// Construction and deserialization enforce the same bounded canonical grammar.
16/// A checked key establishes identity syntax, not allocation or open authority.
17#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
18pub struct StableKey(String);
19
20impl<'de> Deserialize<'de> for StableKey {
21    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
22        // Retain the serialized newtype shape before checking its owned text.
23        #[derive(Deserialize)]
24        #[serde(rename = "StableKey")]
25        struct Text(String);
26
27        let Text(value) = Text::deserialize(deserializer)?;
28        validate(&value).map_err(D::Error::custom)?;
29        Ok(Self(value))
30    }
31}
32
33impl StableKey {
34    /// Parse and validate a canonical stable key string.
35    ///
36    /// Keys are bounded lowercase ASCII dot-separated names ending in a
37    /// nonzero `.vN` suffix.
38    pub fn parse(value: impl AsRef<str>) -> Result<Self, StableKeyError> {
39        let value = value.as_ref();
40        validate(value)?;
41        Ok(Self(value.to_string()))
42    }
43
44    /// Borrow the canonical stable-key string.
45    #[must_use]
46    pub fn as_str(&self) -> &str {
47        &self.0
48    }
49
50    /// Consume the key and return the canonical stable-key string.
51    #[must_use]
52    pub fn into_string(self) -> String {
53        self.0
54    }
55}
56
57impl AsRef<str> for StableKey {
58    fn as_ref(&self) -> &str {
59        self.as_str()
60    }
61}
62
63impl fmt::Display for StableKey {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter.write_str(self.as_str())
66    }
67}
68
69impl FromStr for StableKey {
70    type Err = StableKeyError;
71
72    fn from_str(value: &str) -> Result<Self, Self::Err> {
73        Self::parse(value)
74    }
75}
76
77/// Stable-key grammar validation failure.
78#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
79#[error("stable key '{stable_key}' is invalid: {reason}")]
80pub struct StableKeyError {
81    /// Rejected stable-key string.
82    pub stable_key: String,
83    /// Stable-key grammar failure.
84    pub reason: &'static str,
85}
86
87pub fn validate(stable_key: &str) -> Result<(), StableKeyError> {
88    if stable_key.is_empty() {
89        return invalid(stable_key, "must not be empty");
90    }
91    if stable_key.len() > MAX_KEY_BYTES {
92        return invalid(stable_key, "must be at most 128 bytes");
93    }
94    if !stable_key.is_ascii() {
95        return invalid(stable_key, "must be ASCII");
96    }
97    if stable_key.bytes().any(|byte| byte.is_ascii_uppercase()) {
98        return invalid(stable_key, "must be lowercase");
99    }
100    if stable_key
101        .bytes()
102        .any(|byte| matches!(byte, b'\t'..=b'\r' | b' '))
103    {
104        return invalid(stable_key, "must not contain whitespace");
105    }
106    if stable_key.bytes().any(|byte| matches!(byte, b'/' | b'-')) {
107        return invalid(stable_key, "must not contain slashes or hyphens");
108    }
109    if stable_key.starts_with('.') || stable_key.ends_with('.') {
110        return invalid(stable_key, "must not start or end with a dot");
111    }
112
113    let Some(version_index) = stable_key
114        .as_bytes()
115        .windows(2)
116        .rposition(|pair| pair == b".v")
117    else {
118        return invalid(stable_key, "must end with .vN");
119    };
120    let version = &stable_key[version_index + 2..];
121    if version.is_empty()
122        || version.starts_with('0')
123        || !version.bytes().all(|byte| byte.is_ascii_digit())
124    {
125        return invalid(stable_key, "version suffix must be nonzero .vN");
126    }
127
128    let prefix = &stable_key[..version_index];
129    if prefix.is_empty() {
130        return invalid(
131            stable_key,
132            "must contain at least one segment before version",
133        );
134    }
135
136    for segment in prefix.as_bytes().split(|byte| *byte == b'.') {
137        if let Err(reason) = validate_segment(segment) {
138            return invalid(stable_key, reason);
139        }
140    }
141
142    Ok(())
143}
144
145// A namespace plus its synthetic `v1` suffix must fit the same key grammar.
146// Borrow the prefix rather than allocating a temporary key just to discard it.
147pub fn is_key_prefix(value: &str) -> bool {
148    let Some(prefix) = value.strip_suffix('.') else {
149        return false;
150    };
151    value.len() <= MAX_KEY_BYTES - "v1".len()
152        && prefix
153            .as_bytes()
154            .split(|byte| *byte == b'.')
155            .all(|segment| validate_segment(segment).is_ok())
156}
157
158fn validate_segment(segment: &[u8]) -> Result<(), &'static str> {
159    let mut bytes = segment.iter().copied();
160    let Some(first) = bytes.next() else {
161        return Err("must not contain empty segments");
162    };
163    if !first.is_ascii_lowercase() {
164        return Err("segments must start with a lowercase letter");
165    }
166    if !bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') {
167        return Err("segments may contain only lowercase letters, digits, and underscores");
168    }
169    Ok(())
170}
171
172fn invalid<T>(stable_key: &str, reason: &'static str) -> Result<T, StableKeyError> {
173    Err(StableKeyError {
174        stable_key: stable_key.to_string(),
175        reason,
176    })
177}