nautilus_common/msgbus/
message.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::fmt::Display;
17
18use bytes::Bytes;
19use serde::{Deserialize, Serialize};
20use ustr::Ustr;
21
22use super::switchboard::CLOSE_TOPIC;
23
24/// Represents a bus message including a topic and serialized payload.
25#[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    /// The topic to publish the message on.
32    pub topic: Ustr,
33    /// The serialized payload for the message.
34    pub payload: Bytes,
35}
36
37impl BusMessage {
38    /// Creates a new [`BusMessage`] instance.
39    pub fn new(topic: Ustr, payload: Bytes) -> Self {
40        debug_assert!(!topic.is_empty());
41        Self { topic, payload }
42    }
43
44    /// Creates a new [`BusMessage`] instance with a string-like topic.
45    ///
46    /// This is a convenience constructor that converts any string-like type
47    /// (implementing `AsRef<str>`) into the required `Ustr` type.
48    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    /// Creates a new [`BusMessage`] instance with the `CLOSE` topic and empty payload.
53    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////////////////////////////////////////////////////////////////////////////////
70// Tests
71////////////////////////////////////////////////////////////////////////////////
72#[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}