nautilus_common/msgbus/
message.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.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 = "nautilus_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#[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}