Skip to main content

engine/events/
event.rs

1//! Event payloads.
2
3use std::collections::BTreeMap;
4
5use crate::core::metadata::MetadataValue;
6use crate::core::object_id::ObjectId;
7use crate::core::timestamp::Timestamp;
8use crate::events::event_type::EventType;
9use crate::security::actor::ActorId;
10
11/// A generic key/value payload attached to an event.
12///
13/// The Engine does not interpret payload values; listeners may attach what
14/// they need.
15#[derive(Clone, Debug, Default, PartialEq)]
16pub struct EventData {
17    fields: BTreeMap<String, MetadataValue>,
18}
19
20impl EventData {
21    /// Creates empty event data.
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// Inserts a value, returning the previous value if any.
27    pub fn insert(
28        &mut self,
29        key: impl Into<String>,
30        value: MetadataValue,
31    ) -> Option<MetadataValue> {
32        self.fields.insert(key.into(), value)
33    }
34
35    /// Removes a key, returning its value if present.
36    pub fn remove(&mut self, key: &str) -> Option<MetadataValue> {
37        self.fields.remove(key)
38    }
39
40    /// Returns the value for a key, if present.
41    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
42        self.fields.get(key)
43    }
44
45    /// Returns all fields.
46    pub fn fields(&self) -> &BTreeMap<String, MetadataValue> {
47        &self.fields
48    }
49}
50
51/// A single event in the Engine's synchronous event chain.
52///
53/// Events are historical records: the referenced object may already be gone
54/// by the time a listener sees an `ObjectDeleted` event.
55#[derive(Clone, Debug, PartialEq)]
56pub struct ObjectEvent {
57    /// The kind of event.
58    pub event_type: EventType,
59    /// The primary object the event concerns.
60    pub object: ObjectId,
61    /// The object's previous parent, when relevant.
62    pub source_parent: Option<ObjectId>,
63    /// The object's new parent, when relevant.
64    pub destination_parent: Option<ObjectId>,
65    /// The actor that caused the event, if any.
66    pub actor: Option<ActorId>,
67    /// The virtual time at which the mutation was committed.
68    pub timestamp: Timestamp,
69    /// Additional event payload.
70    pub data: EventData,
71}
72
73impl ObjectEvent {
74    /// Creates an event with no parent references and no payload.
75    pub fn new(
76        event_type: EventType,
77        object: ObjectId,
78        actor: Option<ActorId>,
79        timestamp: Timestamp,
80    ) -> Self {
81        Self {
82            event_type,
83            object,
84            source_parent: None,
85            destination_parent: None,
86            actor,
87            timestamp,
88            data: EventData::new(),
89        }
90    }
91}