vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! The object store behind the filesystem.
//!
//! [`ObjectStore`] holds every Engine object in a flat map keyed by
//! [`ObjectId`]. Directories reference their children by ID and each object
//! references its parent, so object identity is independent of location:
//! moving an object merely re-parents it.

use std::collections::{BTreeSet, HashMap};

use crate::core::metadata::{Metadata, Name};
use crate::core::object::ObjectKind;
use crate::core::object_id::ObjectId;
use crate::core::timestamp::Timestamp;
use crate::error::Error;

/// A node in the object store.
#[derive(Clone)]
pub(crate) struct ObjectData {
    pub id: ObjectId,
    pub kind: ObjectKind,
    pub parent: Option<ObjectId>,
    pub children: BTreeSet<ObjectId>,
    pub metadata: Metadata,
}

impl ObjectData {
    /// The effective size of the object.
    ///
    /// For files with content this is the content length; for metadata-only
    /// files it is the declared size (or 0); directories have size 0.
    pub fn size(&self) -> u64 {
        match &self.kind {
            ObjectKind::File {
                content: Some(content),
            } => u64::try_from(content.len()).unwrap_or(u64::MAX),
            ObjectKind::File { content: None } => self.metadata.declared_size().unwrap_or(0),
            ObjectKind::Directory => 0,
            // A link's size is its target text, like `stat` on a real link.
            ObjectKind::Symlink { target } => u64::try_from(target.len()).unwrap_or(u64::MAX),
        }
    }
}

/// The flat object store.
///
/// Crate-internal: all mutation goes through [`crate::engine::Engine`], which
/// handles authorization and events.
pub(crate) struct ObjectStore {
    objects: HashMap<ObjectId, ObjectData>,
    next_id: u64,
    root: ObjectId,
}

impl ObjectStore {
    /// Creates an empty store containing only the filesystem root.
    ///
    /// The root is the first allocated object (ID 1); IDs start at 1 so that
    /// 0 is never a valid ID and cannot be used as a sentinel.
    pub fn new() -> Self {
        let mut store = Self {
            objects: HashMap::new(),
            next_id: 1,
            root: ObjectId::new(1),
        };
        let root = store.allocate();
        debug_assert_eq!(root, store.root);
        store.objects.insert(
            root,
            ObjectData {
                id: root,
                kind: ObjectKind::Directory,
                parent: None,
                children: BTreeSet::new(),
                metadata: Metadata::for_root(),
            },
        );
        store
    }

    fn allocate(&mut self) -> ObjectId {
        let id = ObjectId::new(self.next_id);
        self.next_id = self.next_id.saturating_add(1);
        id
    }

    /// The filesystem root object.
    pub fn root(&self) -> ObjectId {
        self.root
    }

    /// Looks up an object by ID.
    pub fn get(&self, id: ObjectId) -> Option<&ObjectData> {
        self.objects.get(&id)
    }

    /// Looks up an object by ID, mutably.
    pub fn get_mut(&mut self, id: ObjectId) -> Option<&mut ObjectData> {
        self.objects.get_mut(&id)
    }

    /// Creates a new object in `parent`.
    ///
    /// The caller must have already authorized the operation and checked the
    /// parent.
    pub fn create(
        &mut self,
        parent: ObjectId,
        name: Name,
        kind: ObjectKind,
        now: Timestamp,
    ) -> Result<ObjectId, Error> {
        self.require_directory(parent)?;
        if self.has_child_named(parent, &name)? {
            return Err(Error::NameAlreadyExists {
                name,
                directory: parent,
            });
        }
        let id = self.allocate();
        self.objects.insert(
            id,
            ObjectData {
                id,
                kind,
                parent: Some(parent),
                children: BTreeSet::new(),
                metadata: Metadata::new(name, now),
            },
        );
        let parent_data = self.objects.get_mut(&parent).expect("parent checked above");
        parent_data.children.insert(id);
        Ok(id)
    }

    /// Creates a detached directory outside the filesystem tree.
    ///
    /// The caller must have already authorized the operation.
    pub fn create_detached(&mut self, name: Name, now: Timestamp) -> Result<ObjectId, Error> {
        let id = self.allocate();
        self.objects.insert(
            id,
            ObjectData {
                id,
                kind: ObjectKind::Directory,
                parent: None,
                children: BTreeSet::new(),
                metadata: Metadata::new(name, now),
            },
        );
        Ok(id)
    }

    /// Removes an object from its parent's child list and returns its old
    /// parent, if any. The object itself remains in the store.
    pub fn detach(&mut self, object: ObjectId) -> Result<Option<ObjectId>, Error> {
        let old_parent = self
            .objects
            .get_mut(&object)
            .ok_or(Error::ObjectNotFound(object))?
            .parent
            .take();
        if let Some(parent) = old_parent {
            self.remove_child(parent, object)?;
        }
        Ok(old_parent)
    }

    /// Makes `object` a child of `parent`.
    ///
    /// The caller must have already checked that `parent` exists, is a
    /// directory, and has no conflicting child name.
    pub fn attach(&mut self, object: ObjectId, parent: ObjectId) -> Result<(), Error> {
        self.require_directory(parent)?;
        let data = self
            .objects
            .get_mut(&object)
            .ok_or(Error::ObjectNotFound(object))?;
        data.parent = Some(parent);
        let parent_data = self.objects.get_mut(&parent).expect("parent checked above");
        parent_data.children.insert(object);
        Ok(())
    }

    /// Removes an object from the store entirely.
    pub fn remove(&mut self, object: ObjectId) -> Result<(), Error> {
        if self.objects.remove(&object).is_none() {
            return Err(Error::ObjectNotFound(object));
        }
        Ok(())
    }

    /// Renames an object.
    ///
    /// The caller must have already checked name conflicts.
    pub fn rename(&mut self, object: ObjectId, name: Name) -> Result<(), Error> {
        let data = self
            .objects
            .get_mut(&object)
            .ok_or(Error::ObjectNotFound(object))?;
        data.metadata.set_name(name);
        Ok(())
    }

    /// Copies an object (and, recursively, its subtree) into `destination`.
    ///
    /// The copy gets a fresh identity and is a faithful clone of the source's
    /// metadata. The caller must have already checked the destination and
    /// cycle conditions.
    pub fn clone_into(
        &mut self,
        source: ObjectId,
        destination: ObjectId,
        name: Name,
    ) -> Result<ObjectId, Error> {
        self.require_directory(destination)?;
        if self.has_child_named(destination, &name)? {
            return Err(Error::NameAlreadyExists {
                name,
                directory: destination,
            });
        }
        let source_clone = self
            .objects
            .get(&source)
            .ok_or(Error::ObjectNotFound(source))?
            .clone();
        let new_id = self.allocate();
        let mut new_data = source_clone;
        new_data.id = new_id;
        new_data.parent = Some(destination);
        new_data.children.clear();
        new_data.metadata.set_name(name);
        let parent_data = self
            .objects
            .get_mut(&destination)
            .expect("parent checked above");
        parent_data.children.insert(new_id);
        self.objects.insert(new_id, new_data);
        Ok(new_id)
    }

    /// Returns `true` if a child of `parent` is named `name`.
    pub fn has_child_named(&self, parent: ObjectId, name: &Name) -> Result<bool, Error> {
        let parent_data = self
            .objects
            .get(&parent)
            .ok_or(Error::ObjectNotFound(parent))?;
        Ok(parent_data.children.iter().any(|child| {
            self.objects
                .get(child)
                .is_some_and(|child_data| child_data.metadata.name() == name)
        }))
    }

    /// Returns `true` if `object` is an ancestor of `node`.
    pub fn is_ancestor_of(&self, object: ObjectId, node: ObjectId) -> bool {
        let mut current = node;
        while let Some(parent) = self.objects.get(&current).and_then(|data| data.parent) {
            if parent == object {
                return true;
            }
            current = parent;
        }
        false
    }

    pub(crate) fn require_directory(&self, id: ObjectId) -> Result<(), Error> {
        match self.objects.get(&id).map(|data| data.kind.is_directory()) {
            None => Err(Error::ObjectNotFound(id)),
            Some(false) => Err(Error::NotADirectory(id)),
            Some(true) => Ok(()),
        }
    }

    fn remove_child(&mut self, parent: ObjectId, child: ObjectId) -> Result<(), Error> {
        let parent_data = self
            .objects
            .get_mut(&parent)
            .ok_or(Error::ObjectNotFound(parent))?;
        parent_data.children.remove(&child);
        Ok(())
    }
}