Skip to main content

ic_memory/
schema.rs

1use serde::{Deserialize, Serialize};
2
3///
4/// SchemaMetadata
5///
6/// Optional diagnostic metadata for an in-place store schema.
7///
8/// This metadata helps humans and frameworks diagnose which schema version was
9/// declared in each generation. It is bounded and validated for durable ledger
10/// encoding, but it does not perform application schema migrations or validate
11/// stable data semantics.
12///
13
14#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
15#[serde(deny_unknown_fields)]
16pub struct SchemaMetadata {
17    /// Optional in-place schema version.
18    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
19    pub(crate) schema_version: Option<u32>,
20}
21
22impl SchemaMetadata {
23    /// Construct schema metadata after validating the persisted encoding bounds.
24    pub fn new(schema_version: Option<u32>) -> Result<Self, SchemaMetadataError> {
25        let metadata = Self { schema_version };
26        metadata.validate()?;
27        Ok(metadata)
28    }
29
30    /// Validate schema metadata encoding rules.
31    pub fn validate(&self) -> Result<(), SchemaMetadataError> {
32        if self.schema_version == Some(0) {
33            return Err(SchemaMetadataError::InvalidVersion);
34        }
35        Ok(())
36    }
37
38    /// Return the optional in-place schema version.
39    #[must_use]
40    pub const fn schema_version(&self) -> Option<u32> {
41        self.schema_version
42    }
43}
44
45///
46/// SchemaMetadataError
47///
48/// Schema metadata validation failure.
49///
50
51#[non_exhaustive]
52#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
53pub enum SchemaMetadataError {
54    /// Schema version zero is reserved for absence.
55    #[error("schema_version must be greater than zero when present")]
56    InvalidVersion,
57}