nautilus_infrastructure/python/redis/
msgbus.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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 bytes::Bytes;
17use futures::{pin_mut, stream::StreamExt};
18use nautilus_common::msgbus::database::MessageBusDatabaseAdapter;
19use nautilus_core::{
20    UUID4,
21    python::{IntoPyObjectNautilusExt, to_pyruntime_err, to_pyvalue_err},
22};
23use nautilus_model::identifiers::TraderId;
24use pyo3::prelude::*;
25
26use crate::redis::msgbus::RedisMessageBusDatabase;
27
28#[pymethods]
29impl RedisMessageBusDatabase {
30    #[new]
31    fn py_new(trader_id: TraderId, instance_id: UUID4, config_json: Vec<u8>) -> PyResult<Self> {
32        let config = serde_json::from_slice(&config_json).map_err(to_pyvalue_err)?;
33        Self::new(trader_id, instance_id, config).map_err(to_pyvalue_err)
34    }
35
36    #[pyo3(name = "is_closed")]
37    fn py_is_closed(&self) -> bool {
38        self.is_closed()
39    }
40
41    #[pyo3(name = "publish")]
42    fn py_publish(&self, topic: String, payload: Vec<u8>) {
43        self.publish(topic, Bytes::from(payload))
44    }
45
46    #[pyo3(name = "stream")]
47    fn py_stream<'py>(
48        &mut self,
49        callback: PyObject,
50        py: Python<'py>,
51    ) -> PyResult<Bound<'py, PyAny>> {
52        let stream_rx = self.get_stream_receiver().map_err(to_pyruntime_err)?;
53        let stream = RedisMessageBusDatabase::stream(stream_rx);
54        pyo3_async_runtimes::tokio::future_into_py(py, async move {
55            pin_mut!(stream);
56            while let Some(msg) = stream.next().await {
57                Python::with_gil(|py| call_python(py, &callback, msg.into_py_any_unwrap(py)));
58            }
59            Ok(())
60        })
61    }
62
63    #[pyo3(name = "close")]
64    fn py_close(&mut self) {
65        self.close()
66    }
67}
68
69fn call_python(py: Python, callback: &PyObject, py_obj: PyObject) {
70    if let Err(e) = callback.call1(py, (py_obj,)) {
71        tracing::error!("Error calling Python: {e}");
72    }
73}