event_engine/
events.rs

1//! Events provide the mechansim by which plugins communicate with each other. Events correspond to
2//! statically typed messages defined by the application.
3use crate::errors::EngineError;
4use zmq::Socket;
5use std::error::Error;
6
7/// An event type in the application. Event types have a name, which be used to
8/// specify subscriptions by components (plugins) in applications.
9/// They also have a filter, which is a byte array that appears at the beginning
10/// of every message of the type. The filter must uniquely determine messages to b
11/// of said type.
12pub trait EventType {
13    /// return the name of the event type
14    // TODO -- can we return String and Vec[u8]?
15    fn get_name(&self) -> String;
16
17    /// compute the byte array filter for all messages of this event type.
18    /// The filter must uniquely determine this event type.  The default
19    /// implementation just returns the event name as bytes.
20    fn get_filter(&self) -> Result<Vec<u8>, EngineError>;
21}
22
23/// Public API for defining events in an application.
24/// Events are typed messages that can be sent over a ZMQ socket. Event are equipped
25/// with functions to
26pub trait Event {
27    /// convert the event to a raw byte array
28    fn to_bytes(&self) -> Result<Vec<u8>, EngineError>;
29
30    fn from_bytes(bytes: Vec<u8>) -> Result<Self, Box<dyn Error>>
31    where
32        Self: Sized;
33
34    /// send an event message to all subscribers
35    fn send(&self, pub_socket: &mut Socket) -> Result<(), EngineError> {
36        let data = self.to_bytes()?;
37        pub_socket.send(data, 0)?;
38        Ok(())
39    }
40}