Skip to main content

ic_memory/
declaration.rs

1use crate::{
2    key::{StableKey, StableKeyError},
3    schema::SchemaMetadata,
4    slot::{MemoryManagerSlot, MemoryManagerSlotError},
5    text::{DiagnosticTextError, validate_diagnostic_text},
6};
7use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
8use std::collections::BTreeSet;
9
10///
11/// AllocationDeclaration
12///
13/// Checked runtime claim that a stable key should own an allocation slot.
14///
15/// Declarations are supplied by the current binary before opening storage.
16/// Construction and decoding check the stable key, label, slot and schema
17/// metadata. A declaration becomes authoritative only after validation against
18/// the recovered ledger and commitment in a generation.
19///
20
21#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct AllocationDeclaration {
24    /// Durable stable key.
25    pub(crate) stable_key: StableKey,
26    /// Claimed allocation slot.
27    pub(crate) slot: MemoryManagerSlot,
28    /// Optional diagnostic label.
29    #[serde(deserialize_with = "deserialize_label")]
30    pub(crate) label: Option<String>,
31    /// Optional diagnostic schema metadata.
32    pub(crate) schema: SchemaMetadata,
33}
34
35impl AllocationDeclaration {
36    /// Build a declaration from raw parts after validating diagnostic metadata.
37    pub fn new(
38        stable_key: impl AsRef<str>,
39        slot: MemoryManagerSlot,
40        label: Option<String>,
41        schema: SchemaMetadata,
42    ) -> Result<Self, DeclarationSnapshotError> {
43        let stable_key = StableKey::parse(stable_key).map_err(DeclarationSnapshotError::Key)?;
44        validate_label(label.as_deref())?;
45        Ok(Self {
46            stable_key,
47            slot,
48            label,
49            schema,
50        })
51    }
52
53    /// Build a `MemoryManager` declaration with a diagnostic label.
54    pub fn memory_manager(
55        stable_key: impl AsRef<str>,
56        id: u8,
57        label: impl Into<String>,
58    ) -> Result<Self, DeclarationSnapshotError> {
59        Self::memory_manager_with_schema(stable_key, id, label, SchemaMetadata::default())
60    }
61
62    /// Build an unlabeled `MemoryManager` declaration.
63    pub fn memory_manager_unlabeled(
64        stable_key: impl AsRef<str>,
65        id: u8,
66    ) -> Result<Self, DeclarationSnapshotError> {
67        Self::memory_manager_unlabeled_with_schema(stable_key, id, SchemaMetadata::default())
68    }
69
70    /// Build a `MemoryManager` declaration with a diagnostic label and schema metadata.
71    pub fn memory_manager_with_schema(
72        stable_key: impl AsRef<str>,
73        id: u8,
74        label: impl Into<String>,
75        schema: SchemaMetadata,
76    ) -> Result<Self, DeclarationSnapshotError> {
77        let slot =
78            MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
79        Self::new(stable_key, slot, Some(label.into()), schema)
80    }
81
82    /// Build an unlabeled `MemoryManager` declaration with schema metadata.
83    pub fn memory_manager_unlabeled_with_schema(
84        stable_key: impl AsRef<str>,
85        id: u8,
86        schema: SchemaMetadata,
87    ) -> Result<Self, DeclarationSnapshotError> {
88        let slot =
89            MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
90        Self::new(stable_key, slot, None, schema)
91    }
92
93    /// Return the durable stable key claimed by this declaration.
94    #[must_use]
95    pub const fn stable_key(&self) -> &StableKey {
96        &self.stable_key
97    }
98
99    /// Return the allocation slot claimed by this declaration.
100    #[must_use]
101    pub const fn slot(&self) -> &MemoryManagerSlot {
102        &self.slot
103    }
104
105    /// Return the optional diagnostic label.
106    #[must_use]
107    pub fn label(&self) -> Option<&str> {
108        self.label.as_deref()
109    }
110
111    /// Return the optional schema metadata.
112    #[must_use]
113    pub const fn schema(&self) -> &SchemaMetadata {
114        &self.schema
115    }
116}
117
118///
119/// DeclarationSnapshot
120///
121/// Immutable runtime declaration snapshot ready for policy and ownership validation.
122///
123/// Construction and decoding enforce the declaration count and unique keys and
124/// slots. A snapshot is not permission to open storage.
125/// [`crate::MemoryRuntime::bootstrap`] owns validation and persistence before
126/// publishing committed allocation authority.
127///
128
129#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
130pub struct DeclarationSnapshot {
131    /// Runtime declarations.
132    declarations: Vec<AllocationDeclaration>,
133}
134
135impl<'de> Deserialize<'de> for DeclarationSnapshot {
136    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
137        #[derive(Deserialize)]
138        #[serde(rename = "DeclarationSnapshot", deny_unknown_fields)]
139        struct Snapshot {
140            #[serde(deserialize_with = "crate::cbor::deserialize_records")]
141            declarations: Vec<AllocationDeclaration>,
142        }
143
144        let snapshot = Snapshot::deserialize(deserializer)?;
145        Self::new(snapshot.declarations).map_err(D::Error::custom)
146    }
147}
148
149impl DeclarationSnapshot {
150    /// Create and validate a declaration snapshot.
151    pub fn new(declarations: Vec<AllocationDeclaration>) -> Result<Self, DeclarationSnapshotError> {
152        validate_declaration_set(&declarations)?;
153        Ok(Self { declarations })
154    }
155
156    /// Return true when the snapshot has no declarations.
157    #[must_use]
158    pub const fn is_empty(&self) -> bool {
159        self.declarations.is_empty()
160    }
161
162    /// Return the number of declarations in the snapshot.
163    #[must_use]
164    pub const fn len(&self) -> usize {
165        self.declarations.len()
166    }
167
168    /// Borrow the sealed declarations.
169    #[must_use]
170    pub fn declarations(&self) -> &[AllocationDeclaration] {
171        &self.declarations
172    }
173
174    pub(crate) fn into_declarations(self) -> Vec<AllocationDeclaration> {
175        self.declarations
176    }
177}
178
179///
180/// DeclarationSnapshotError
181///
182/// Declaration snapshot validation failure.
183#[non_exhaustive]
184#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
185pub enum DeclarationSnapshotError {
186    #[error("at most 255 allocation declarations are supported")]
187    TooManyDeclarations,
188    /// Stable-key grammar failure.
189    #[error(transparent)]
190    Key(StableKeyError),
191    /// `MemoryManager` slot validation failure.
192    #[error(transparent)]
193    MemoryManagerSlot(MemoryManagerSlotError),
194    /// A stable key appeared more than once in one snapshot.
195    #[error("stable key '{0}' is declared more than once")]
196    DuplicateStableKey(StableKey),
197    /// An allocation slot appeared more than once in one snapshot.
198    #[error("allocation slot '{0:?}' is declared more than once")]
199    DuplicateSlot(MemoryManagerSlot),
200    /// Present declaration labels must be non-empty.
201    #[error("allocation declaration label must not be empty when present")]
202    EmptyLabel,
203    /// Declaration labels must stay bounded for durable ledger storage.
204    #[error("allocation declaration label must be at most 256 bytes")]
205    LabelTooLong,
206    /// Declaration labels must not require Unicode normalization.
207    #[error("allocation declaration label must be ASCII")]
208    NonAsciiLabel,
209    /// Declaration labels must be printable metadata.
210    #[error("allocation declaration label must not contain ASCII control characters")]
211    ControlCharacterLabel,
212}
213
214fn validate_label(label: Option<&str>) -> Result<(), DeclarationSnapshotError> {
215    let Some(label) = label else {
216        return Ok(());
217    };
218    validate_diagnostic_text(label).map_err(|error| match error {
219        DiagnosticTextError::Empty => DeclarationSnapshotError::EmptyLabel,
220        DiagnosticTextError::TooLong => DeclarationSnapshotError::LabelTooLong,
221        DiagnosticTextError::NonAscii => DeclarationSnapshotError::NonAsciiLabel,
222        DiagnosticTextError::ControlCharacter => DeclarationSnapshotError::ControlCharacterLabel,
223    })
224}
225
226// Decode explicitly present optional labels through the same constructor rule.
227// Retain the owned string; no intermediate label type or compatibility default.
228fn deserialize_label<'de, D: Deserializer<'de>>(
229    deserializer: D,
230) -> Result<Option<String>, D::Error> {
231    let label = Option::<String>::deserialize(deserializer)?;
232    validate_label(label.as_deref()).map_err(D::Error::custom)?;
233    Ok(label)
234}
235
236fn validate_declaration_set(
237    declarations: &[AllocationDeclaration],
238) -> Result<(), DeclarationSnapshotError> {
239    if declarations.len() > crate::constants::MAX_ALLOCATIONS {
240        return Err(DeclarationSnapshotError::TooManyDeclarations);
241    }
242    let mut keys = BTreeSet::new();
243    let mut slots = [false; crate::constants::MAX_ALLOCATIONS];
244
245    for declaration in declarations {
246        let occupied = &mut slots[usize::from(declaration.slot.id())];
247        if *occupied {
248            return Err(DeclarationSnapshotError::DuplicateSlot(
249                declaration.slot.clone(),
250            ));
251        }
252        *occupied = true;
253        if !keys.insert(&declaration.stable_key) {
254            return Err(DeclarationSnapshotError::DuplicateStableKey(
255                declaration.stable_key.clone(),
256            ));
257        }
258    }
259
260    Ok(())
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::slot::MemoryManagerSlot;
267
268    fn declaration(key: &str, id: u8) -> AllocationDeclaration {
269        AllocationDeclaration::new(
270            key,
271            MemoryManagerSlot::new(id).expect("usable slot"),
272            None,
273            SchemaMetadata::default(),
274        )
275        .expect("declaration")
276    }
277
278    #[test]
279    fn declaration_rejects_unbounded_label_metadata() {
280        let err = AllocationDeclaration::new(
281            "app.users.v1",
282            MemoryManagerSlot::new(100).expect("usable slot"),
283            Some("x".repeat(257)),
284            SchemaMetadata::default(),
285        )
286        .expect_err("label too long");
287
288        assert_eq!(err, DeclarationSnapshotError::LabelTooLong);
289    }
290
291    #[test]
292    fn memory_manager_declaration_constructor_builds_common_declaration() {
293        let declaration = AllocationDeclaration::memory_manager("app.orders.v1", 100, "orders")
294            .expect("declaration");
295
296        assert_eq!(declaration.stable_key.as_str(), "app.orders.v1");
297        assert_eq!(
298            declaration.slot,
299            MemoryManagerSlot::new(100).expect("usable slot")
300        );
301        assert_eq!(declaration.label.as_deref(), Some("orders"));
302        assert_eq!(declaration.schema, SchemaMetadata::default());
303    }
304
305    #[test]
306    fn memory_manager_declaration_constructor_rejects_invalid_slot() {
307        let err = AllocationDeclaration::memory_manager("app.orders.v1", u8::MAX, "orders")
308            .expect_err("sentinel must fail");
309
310        assert!(matches!(
311            err,
312            DeclarationSnapshotError::MemoryManagerSlot(_)
313        ));
314    }
315
316    #[test]
317    fn snapshot_decode_rejects_unusable_memory_manager_slot() {
318        let snapshot = DeclarationSnapshot::new(vec![declaration("app.orders.v1", 100)]).unwrap();
319        let mut value = serde_json::to_value(snapshot).unwrap();
320        value["declarations"][0]["slot"]["slot"]["MemoryManagerId"] = serde_json::json!(255);
321        assert!(serde_json::from_value::<DeclarationSnapshot>(value).is_err());
322    }
323
324    #[test]
325    fn rejects_duplicate_keys() {
326        let err = DeclarationSnapshot::new(vec![
327            declaration("app.users.v1", 100),
328            declaration("app.users.v1", 101),
329        ])
330        .expect_err("duplicate key");
331
332        assert_eq!(
333            err,
334            DeclarationSnapshotError::DuplicateStableKey(StableKey::parse("app.users.v1").unwrap())
335        );
336    }
337
338    #[test]
339    fn rejects_duplicate_slots() {
340        for second_key in ["app.orders.v1", "app.users.v1"] {
341            let err = DeclarationSnapshot::new(vec![
342                declaration("app.users.v1", 100),
343                declaration(second_key, 100),
344            ])
345            .expect_err("duplicate slot precedes duplicate key");
346
347            assert_eq!(
348                err,
349                DeclarationSnapshotError::DuplicateSlot(MemoryManagerSlot::new(100).unwrap())
350            );
351        }
352    }
353}