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