querent_synapse/comm/types/
message.rs

1// Import necessary items from the pyo3 crate
2use pyo3::{
3	exceptions::PyTypeError,
4	prelude::*,
5	types::{PyDict, PyString},
6};
7
8// Define an enumeration for different event types
9#[derive(Clone, Debug, PartialEq, Eq, Hash)]
10pub enum MessageType {
11	Start,
12	Stop,
13	Pause,
14	Resume,
15	Restart,
16	Status,
17	Metrics,
18}
19
20// Implement conversion from Python object to MessageType
21impl<'a> FromPyObject<'a> for MessageType {
22	fn extract(ob: &'a PyAny) -> PyResult<Self> {
23		// Try to extract a string from the Python object
24		if let Ok(message_type) = ob.extract::<&str>() {
25			// Match the string to determine the EventType
26			match message_type {
27				"start" => Ok(MessageType::Start),
28				"stop" => Ok(MessageType::Stop),
29				"pause" => Ok(MessageType::Pause),
30				"resume" => Ok(MessageType::Resume),
31				"restart" => Ok(MessageType::Restart),
32				"status" => Ok(MessageType::Status),
33				"metrics" => Ok(MessageType::Metrics),
34				// If the string does not match any known EventType, return an error
35				_ => Err(PyErr::new::<PyTypeError, _>("Invalid message type")),
36			}
37		} else {
38			// If extraction fails, return an error
39			Err(PyErr::new::<PyTypeError, _>("Invalid message type"))
40		}
41	}
42}
43
44// Implement conversion from MessageType to Python object\
45impl IntoPy<PyObject> for MessageType {
46	fn into_py(self, py: Python) -> PyObject {
47		// Create a new Python string
48		let string = PyString::new(py, &format!("{:?}", self));
49		// Return the string
50		string.into()
51	}
52}
53
54// Define a structure to represent the state of an event
55#[derive(Clone, Debug, PartialEq)]
56pub struct MessageState {
57	pub message_type: MessageType,
58	pub timestamp: f64,
59	pub payload: String,
60}
61
62// Implement conversion from Python object to MessageState
63impl<'a> FromPyObject<'a> for MessageState {
64	fn extract(ob: &'a PyAny) -> PyResult<Self> {
65		// Extract values for event_type, timestamp, and payload from the Python object
66		let message_type = ob.get_item("message_type")?.extract()?;
67		let timestamp = ob.get_item("timestamp")?.extract()?;
68		let payload = ob.get_item("payload")?.extract()?;
69		// Create and return an MessageState instance
70		Ok(MessageState { message_type, timestamp, payload })
71	}
72}
73
74// Implement conversion from MessageState to Python object
75impl IntoPy<PyObject> for MessageState {
76	fn into_py(self, py: Python) -> PyObject {
77		// Create a new Python dictionary
78		let dict = PyDict::new(py);
79		// Insert the message_type, timestamp, and payload into the dictionary
80		dict.set_item("message_type", self.message_type.into_py(py)).unwrap();
81		dict.set_item("timestamp", self.timestamp).unwrap();
82		dict.set_item("payload", self.payload).unwrap();
83		// Return the dictionary
84		dict.into()
85	}
86}