anycms_event/event.rs
1//! Core [`Event`] trait definition.
2//!
3//! All events must implement this trait to be publishable on the event bus.
4
5/// Core trait that all events must implement.
6///
7/// Events must be `Clone + Send + Sync + 'static` so they can be type-erased
8/// via `Arc<dyn Any + Send + Sync>` and downcast back to the concrete type
9/// in subscriber handlers.
10///
11/// # Example
12///
13/// ```ignore
14/// #[derive(Clone, Debug)]
15/// struct UserCreated {
16/// user_id: u64,
17/// name: String,
18/// }
19///
20/// impl Event for UserCreated {
21/// fn event_name() -> &'static str { "user.created" }
22///
23/// fn topic() -> &'static str { "user" }
24/// }
25/// ```
26pub trait Event: Clone + Send + Sync + 'static {
27 /// Unique name for this event type, used for routing and topic matching.
28 fn event_name() -> &'static str
29 where
30 Self: Sized;
31
32 /// Topic this event belongs to. Default is the event_name itself.
33 ///
34 /// Override this when multiple event types share a common topic namespace,
35 /// e.g., `"user"` for both `UserCreated` and `UserDeleted`.
36 fn topic() -> &'static str
37 where
38 Self: Sized,
39 {
40 Self::event_name()
41 }
42
43 /// Serialize event to JSON for observers like TriggerRuleEngine.
44 /// Returns `None` by default — events that implement `Serialize` can override
45 /// to provide their JSON representation.
46 fn to_json(&self) -> Option<serde_json::Value> {
47 let _ = self;
48 None
49 }
50
51 /// Deserialize event from a JSON string.
52 ///
53 /// Default returns `None` — events that implement `Deserialize` can override
54 /// to provide deserialization. The `#[derive(Event)]` macro auto-generates
55 /// this using `serde_json::from_str`.
56 fn from_json(json: &str) -> Option<Self>
57 where
58 Self: Sized,
59 {
60 let _ = json;
61 None
62 }
63}