vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Object metadata.
//!
//! Metadata is generic: names, timestamps, a reference to an owning
//! principal, opaque authorization data, and an extensible key/value store.
//! The Engine stores extension values without understanding their meaning;
//! the OS assigns semantics.

use std::collections::BTreeMap;
use std::fmt;

use crate::error::Error;
use crate::filesystem::path::SEPARATOR;
use crate::security::authorization::{ActorId, AuthorizationData};

use super::timestamp::Timestamp;

/// The name of the filesystem root.
///
/// The root is the only object whose name is not a path component.
pub const ROOT_NAME: &str = "/";

/// The name of an object, as stored in its metadata.
///
/// Valid names are non-empty, contain no path separator and no NUL byte, and
/// are neither `.` nor `..`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Name(String);

impl Name {
    /// Validates and constructs a name.
    pub fn new(name: &str) -> Result<Self, Error> {
        if name.is_empty() {
            return Err(Error::InvalidName(name.to_owned()));
        }
        if name.contains(SEPARATOR) {
            return Err(Error::InvalidName(name.to_owned()));
        }
        if name.contains('\0') {
            return Err(Error::InvalidName(name.to_owned()));
        }
        if name == "." || name == ".." {
            return Err(Error::InvalidName(name.to_owned()));
        }
        Ok(Self(name.to_owned()))
    }

    /// The name of the filesystem root.
    pub fn root() -> Self {
        Self(ROOT_NAME.to_owned())
    }

    /// Returns the name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns `true` for the root name.
    pub fn is_root(&self) -> bool {
        self.0 == ROOT_NAME
    }
}

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A generic metadata value for the extensible key/value store.
///
/// Used both for metadata extensions and for event payloads. The Engine does
/// not interpret these values.
#[derive(Clone, PartialEq, Debug)]
pub enum MetadataValue {
    /// A string value.
    String(String),
    /// A signed integer value.
    Integer(i64),
    /// An unsigned integer value.
    Unsigned(u64),
    /// A floating-point value.
    Float(f64),
    /// A boolean value.
    Boolean(bool),
}

/// Metadata for an Engine object.
///
/// Metadata is owned by the object and moves with it; it is not tied to the
/// object's path.
#[derive(Clone, Debug, PartialEq)]
pub struct Metadata {
    name: Name,
    created: Timestamp,
    modified: Timestamp,
    accessed: Timestamp,
    owner: Option<ActorId>,
    authorization: AuthorizationData,
    version: Option<String>,
    declared_size: Option<u64>,
    extensions: BTreeMap<String, MetadataValue>,
}

impl Metadata {
    /// Creates metadata for a new object, with all timestamps set to `now`.
    pub(crate) fn new(name: Name, now: Timestamp) -> Self {
        Self {
            name,
            created: now,
            modified: now,
            accessed: now,
            owner: None,
            authorization: AuthorizationData::new(),
            version: None,
            declared_size: None,
            extensions: BTreeMap::new(),
        }
    }

    /// Creates the metadata of the filesystem root.
    ///
    /// The root is created by the store itself, before any clock exists, so
    /// its timestamps are the virtual epoch.
    pub(crate) fn for_root() -> Self {
        Self {
            name: Name::root(),
            created: Timestamp::ZERO,
            modified: Timestamp::ZERO,
            accessed: Timestamp::ZERO,
            owner: None,
            authorization: AuthorizationData::new(),
            version: None,
            declared_size: None,
            extensions: BTreeMap::new(),
        }
    }

    /// The object's name.
    pub fn name(&self) -> &Name {
        &self.name
    }

    /// The creation time.
    pub fn created(&self) -> Timestamp {
        self.created
    }

    /// The last modification time.
    pub fn modified(&self) -> Timestamp {
        self.modified
    }

    /// The last access time.
    pub fn accessed(&self) -> Timestamp {
        self.accessed
    }

    /// The owning principal, if any.
    pub fn owner(&self) -> Option<ActorId> {
        self.owner
    }

    /// The opaque authorization data.
    pub fn authorization(&self) -> &AuthorizationData {
        &self.authorization
    }

    /// An optional version string (for example `17.2` for a bundle).
    pub fn version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// The size declared for metadata-only files, if any.
    pub fn declared_size(&self) -> Option<u64> {
        self.declared_size
    }

    /// A single extension value by key.
    pub fn extension(&self, key: &str) -> Option<&MetadataValue> {
        self.extensions.get(key)
    }

    /// All extension values.
    pub fn extensions(&self) -> &BTreeMap<String, MetadataValue> {
        &self.extensions
    }

    pub(crate) fn set_name(&mut self, name: Name) {
        self.name = name;
    }

    pub(crate) fn set_modified(&mut self, timestamp: Timestamp) {
        self.modified = timestamp;
    }

    pub(crate) fn set_accessed(&mut self, timestamp: Timestamp) {
        self.accessed = timestamp;
    }

    pub(crate) fn set_owner(&mut self, owner: Option<ActorId>) {
        self.owner = owner;
    }

    pub(crate) fn set_authorization(&mut self, authorization: AuthorizationData) {
        self.authorization = authorization;
    }

    /// Applies a patch. Fields not present in the patch are left unchanged.
    ///
    /// The whole patch is validated before anything is applied, so a patch
    /// with any invalid key leaves the metadata exactly as it was.
    pub(crate) fn apply(&mut self, patch: &MetadataPatch) -> Result<(), Error> {
        for key in patch.extensions.keys() {
            validate_metadata_key(key)?;
        }
        if let Some(version) = &patch.version {
            self.version = version.clone();
        }
        if let Some(declared_size) = &patch.declared_size {
            self.declared_size = *declared_size;
        }
        for (key, value) in &patch.extensions {
            match value {
                Some(value) => {
                    self.extensions.insert(key.clone(), value.clone());
                }
                None => {
                    self.extensions.remove(key);
                }
            }
        }
        Ok(())
    }
}

/// Validates a metadata extension key.
fn validate_metadata_key(key: &str) -> Result<(), Error> {
    if key.is_empty() {
        return Err(Error::InvalidMetadataKey(key.to_owned()));
    }
    Ok(())
}

/// A set of metadata changes to apply atomically.
///
/// The outer `Option` indicates whether the field is part of the patch; the
/// inner `Option` is the new value, where `None` clears the field. For
/// [`MetadataPatch::extensions`], a `None` value removes the key.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MetadataPatch {
    /// The new version, or `Some(None)` to clear it.
    pub version: Option<Option<String>>,
    /// The new declared size, or `Some(None)` to clear it.
    pub declared_size: Option<Option<u64>>,
    /// Extension changes: key to new value, or `None` to remove the key.
    pub extensions: BTreeMap<String, Option<MetadataValue>>,
}

impl MetadataPatch {
    /// Returns `true` when the patch changes nothing.
    pub fn is_empty(&self) -> bool {
        self.version.is_none() && self.declared_size.is_none() && self.extensions.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_names_are_accepted() {
        for name in ["file.txt", "ls", "a b", "снег", "-"] {
            assert!(Name::new(name).is_ok(), "expected {name:?} to be valid");
        }
    }

    #[test]
    fn invalid_names_are_rejected() {
        for name in ["", "/", "a/b", "a\0b", ".", ".."] {
            assert_eq!(
                Name::new(name).err(),
                Some(Error::InvalidName(name.to_owned())),
                "expected {name:?} to be invalid"
            );
        }
    }

    #[test]
    fn patch_applies_only_present_fields() {
        let mut metadata = Metadata::new(Name::new("a").unwrap(), Timestamp::ZERO);
        let patch = MetadataPatch {
            version: Some(Some("1.0".to_owned())),
            ..MetadataPatch::default()
        };
        metadata.apply(&patch).unwrap();
        assert_eq!(metadata.version(), Some("1.0"));
        assert_eq!(metadata.declared_size(), None);
    }

    #[test]
    fn patch_removes_extensions_with_none() {
        let mut metadata = Metadata::new(Name::new("a").unwrap(), Timestamp::ZERO);
        metadata
            .apply(&MetadataPatch {
                extensions: BTreeMap::from([(
                    "kind".to_owned(),
                    Some(MetadataValue::String("bundle".to_owned())),
                )]),
                ..MetadataPatch::default()
            })
            .unwrap();
        assert!(metadata.extension("kind").is_some());

        metadata
            .apply(&MetadataPatch {
                extensions: BTreeMap::from([("kind".to_owned(), None)]),
                ..MetadataPatch::default()
            })
            .unwrap();
        assert!(metadata.extension("kind").is_none());
    }
}