nautilus_infrastructure/python/redis/
msgbus.rs1use 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}