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