vce-engine 0.1.1

The generic state substrate of the Virtual Computing Engine (VCE)
Documentation
//! Event payloads.

use std::collections::BTreeMap;

use crate::core::metadata::MetadataValue;
use crate::core::object_id::ObjectId;
use crate::core::timestamp::Timestamp;
use crate::events::event_type::EventType;
use crate::security::actor::ActorId;

/// A generic key/value payload attached to an event.
///
/// The Engine does not interpret payload values; listeners may attach what
/// they need.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventData {
    fields: BTreeMap<String, MetadataValue>,
}

impl EventData {
    /// Creates empty event data.
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a value, returning the previous value if any.
    pub fn insert(
        &mut self,
        key: impl Into<String>,
        value: MetadataValue,
    ) -> Option<MetadataValue> {
        self.fields.insert(key.into(), value)
    }

    /// Removes a key, returning its value if present.
    pub fn remove(&mut self, key: &str) -> Option<MetadataValue> {
        self.fields.remove(key)
    }

    /// Returns the value for a key, if present.
    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
        self.fields.get(key)
    }

    /// Returns all fields.
    pub fn fields(&self) -> &BTreeMap<String, MetadataValue> {
        &self.fields
    }
}

/// A single event in the Engine's synchronous event chain.
///
/// Events are historical records: the referenced object may already be gone
/// by the time a listener sees an `ObjectDeleted` event.
#[derive(Clone, Debug, PartialEq)]
pub struct ObjectEvent {
    /// The kind of event.
    pub event_type: EventType,
    /// The primary object the event concerns.
    pub object: ObjectId,
    /// The object's previous parent, when relevant.
    pub source_parent: Option<ObjectId>,
    /// The object's new parent, when relevant.
    pub destination_parent: Option<ObjectId>,
    /// The actor that caused the event, if any.
    pub actor: Option<ActorId>,
    /// The virtual time at which the mutation was committed.
    pub timestamp: Timestamp,
    /// Additional event payload.
    pub data: EventData,
}

impl ObjectEvent {
    /// Creates an event with no parent references and no payload.
    pub fn new(
        event_type: EventType,
        object: ObjectId,
        actor: Option<ActorId>,
        timestamp: Timestamp,
    ) -> Self {
        Self {
            event_type,
            object,
            source_parent: None,
            destination_parent: None,
            actor,
            timestamp,
            data: EventData::new(),
        }
    }
}