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 = "posei_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)]
73mod tests {
74 use bytes::Bytes;
75 use rstest::rstest;
76
77 use super::*;
78
79 #[rstest]
80 #[case("test/topic", "payload data")]
81 #[case("events/trading", "Another payload")]
82 fn test_with_str_topic_str(#[case] topic: &str, #[case] payload_str: &str) {
83 let payload = Bytes::from(payload_str.to_string());
84
85 let message = BusMessage::with_str_topic(topic, payload.clone());
86
87 assert_eq!(message.topic.as_str(), topic);
88 assert_eq!(message.payload, payload);
89 }
90
91 #[rstest]
92 fn test_with_str_topic_string() {
93 let topic_string = String::from("orders/new");
94 let payload = Bytes::from("order payload data");
95
96 let message = BusMessage::with_str_topic(topic_string.clone(), payload.clone());
97
98 assert_eq!(message.topic.as_str(), topic_string);
99 assert_eq!(message.payload, payload);
100 }
101
102 #[rstest]
103 fn test_new_close() {
104 let message = BusMessage::new_close();
105
106 assert_eq!(message.topic.as_str(), "CLOSE");
107 assert!(message.payload.is_empty());
108 }
109}