nautilus_common/python/
handler.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 2Nautech 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::any::Any;
17
18use nautilus_core::python::clone_py_object;
19use pyo3::prelude::*;
20use ustr::Ustr;
21
22use crate::msgbus::handler::MessageHandler;
23
24#[cfg_attr(
25    feature = "python",
26    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.common")
27)]
28#[derive(Debug)]
29pub struct PythonMessageHandler {
30    id: Ustr,
31    handler: PyObject,
32}
33
34impl Clone for PythonMessageHandler {
35    fn clone(&self) -> Self {
36        Self {
37            id: self.id,
38            handler: clone_py_object(&self.handler),
39        }
40    }
41}
42
43#[pymethods]
44impl PythonMessageHandler {
45    /// Creates a new [`PythonMessageHandler`] instance.
46    #[new]
47    #[must_use]
48    pub fn new(id: &str, handler: PyObject) -> Self {
49        let id = Ustr::from(id);
50        Self { id, handler }
51    }
52}
53
54impl MessageHandler for PythonMessageHandler {
55    #[allow(unused_variables)]
56    fn handle(&self, message: &dyn Any) {
57        // TODO: convert message to PyObject
58        let py_event = ();
59        let result =
60            pyo3::Python::with_gil(|py| self.handler.call_method1(py, "handle", (py_event,)));
61        if let Err(e) = result {
62            eprintln!("Error calling handle method: {e:?}");
63        }
64    }
65
66    fn id(&self) -> Ustr {
67        self.id
68    }
69
70    fn as_any(&self) -> &dyn Any {
71        self
72    }
73}