nautilus_common/msgbus/
message.rs1use std::fmt::Display;
17
18use bytes::Bytes;
19use serde::{Deserialize, Serialize};
20use ustr::Ustr;
21
22use super::switchboard::CLOSE_TOPIC;
23
24#[derive(Clone, Debug, Serialize, Deserialize)]
26#[cfg_attr(
27 feature = "python",
28 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.common")
29)]
30pub struct BusMessage {
31 pub topic: Ustr,
33 pub payload: Bytes,
35}
36
37impl BusMessage {
38 pub fn new(topic: Ustr, payload: Bytes) -> Self {
40 debug_assert!(!topic.is_empty());
41 Self { topic, payload }
42 }
43
44 pub fn with_str_topic<T: AsRef<str>>(topic: T, payload: Bytes) -> Self {
49 Self::new(Ustr::from(topic.as_ref()), payload)
50 }
51
52 pub fn new_close() -> Self {
54 Self::with_str_topic(CLOSE_TOPIC, Bytes::new())
55 }
56}
57
58impl Display for BusMessage {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 write!(
61 f,
62 "[{}] {}",
63 self.topic,
64 String::from_utf8_lossy(&self.payload)
65 )
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use bytes::Bytes;
72 use rstest::rstest;
73
74 use super::*;
75
76 #[rstest]
77 #[case("test/topic", "payload data")]
78 #[case("events/trading", "Another payload")]
79 fn test_with_str_topic_str(#[case] topic: &str, #[case] payload_str: &str) {
80 let payload = Bytes::from(payload_str.to_string());
81
82 let message = BusMessage::with_str_topic(topic, payload.clone());
83
84 assert_eq!(message.topic.as_str(), topic);
85 assert_eq!(message.payload, payload);
86 }
87
88 #[rstest]
89 fn test_with_str_topic_string() {
90 let topic_string = String::from("orders/new");
91 let payload = Bytes::from("order payload data");
92
93 let message = BusMessage::with_str_topic(topic_string.clone(), payload.clone());
94
95 assert_eq!(message.topic.as_str(), topic_string);
96 assert_eq!(message.payload, payload);
97 }
98
99 #[rstest]
100 fn test_new_close() {
101 let message = BusMessage::new_close();
102
103 assert_eq!(message.topic.as_str(), "CLOSE");
104 assert!(message.payload.is_empty());
105 }
106}