nautilus_core/python/mod.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
16#![allow(clippy::doc_markdown, reason = "Python docstrings")]
17
18//! Python bindings and interoperability built using [`PyO3`](https://pyo3.rs).
19
20#![allow(
21 deprecated,
22 reason = "pyo3-stub-gen currently relies on PyO3 initialization helpers marked as deprecated"
23)]
24//!
25//! This sub-module groups together the Rust code that is *only* required when compiling the
26//! `python` feature flag. It provides thin adapters so that NautilusTrader functionality can be
27//! consumed from the `nautilus_trader` Python package without sacrificing type-safety or
28//! performance.
29
30pub mod casing;
31pub mod datetime;
32pub mod enums;
33pub mod parsing;
34pub mod serialization;
35/// String manipulation utilities for Python.
36pub mod string;
37pub mod uuid;
38pub mod version;
39
40use std::fmt::Display;
41
42use pyo3::{
43 Py,
44 conversion::IntoPyObjectExt,
45 exceptions::{PyRuntimeError, PyTypeError, PyValueError},
46 prelude::*,
47 types::PyString,
48 wrap_pyfunction,
49};
50use pyo3_stub_gen::derive::gen_stub_pyfunction;
51
52use crate::{
53 UUID4,
54 consts::{NAUTILUS_USER_AGENT, NAUTILUS_VERSION},
55 datetime::{
56 MILLISECONDS_IN_SECOND, NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND,
57 NANOSECONDS_IN_SECOND,
58 },
59};
60
61/// Safely clones a Python object by acquiring the GIL and properly managing reference counts.
62///
63/// This function exists to break reference cycles between Rust and Python that can occur
64/// when using `Arc<Py<PyAny>>` in callback-holding structs. The original design wrapped
65/// Python callbacks in `Arc` for thread-safe sharing, but this created circular references:
66///
67/// 1. Rust `Arc` holds Python objects → increases Python reference count.
68/// 2. Python objects might reference Rust objects → creates cycles.
69/// 3. Neither side can be garbage collected → memory leak.
70///
71/// By using plain `Py<PyAny>` with GIL-based cloning instead of `Arc<Py<PyAny>>`, we:
72/// - Avoid circular references between Rust and Python memory management.
73/// - Ensure proper Python reference counting under the GIL.
74/// - Allow both Rust and Python garbage collectors to work correctly.
75///
76/// # Safety
77///
78/// This function properly acquires the Python GIL before performing the clone operation,
79/// ensuring thread-safe access to the Python object and correct reference counting.
80#[must_use]
81pub fn clone_py_object(obj: &Py<PyAny>) -> Py<PyAny> {
82 Python::attach(|py| obj.clone_ref(py))
83}
84
85/// Extend `IntoPyObjectExt` helper trait to unwrap `Py<PyAny>` after conversion.
86pub trait IntoPyObjectNautilusExt<'py>: IntoPyObjectExt<'py> {
87 /// Convert `self` into a [`Py<PyAny>`] while *panicking* if the conversion fails.
88 ///
89 /// This is a convenience wrapper around [`IntoPyObjectExt::into_py_any`] that avoids the
90 /// cumbersome `Result` handling when we are certain that the conversion cannot fail (for
91 /// instance when we are converting primitives or other types that already implement the
92 /// necessary PyO3 traits).
93 #[inline]
94 fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny> {
95 self.into_py_any(py)
96 .expect("Failed to convert type to Py<PyAny>")
97 }
98}
99
100impl<'py, T> IntoPyObjectNautilusExt<'py> for T where T: IntoPyObjectExt<'py> {}
101
102/// Gets the type name for the given Python `obj`.
103///
104/// # Errors
105///
106/// Returns a error if accessing the type name fails.
107pub fn get_pytype_name<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyString>> {
108 obj.get_type().name()
109}
110
111/// Converts any type that implements `Display` to a Python `ValueError`.
112///
113/// # Errors
114///
115/// Returns a Python error with the error string.
116pub fn to_pyvalue_err(e: impl Display) -> PyErr {
117 PyValueError::new_err(e.to_string())
118}
119
120/// Converts any type that implements `Display` to a Python `TypeError`.
121///
122/// # Errors
123///
124/// Returns a Python error with the error string.
125pub fn to_pytype_err(e: impl Display) -> PyErr {
126 PyTypeError::new_err(e.to_string())
127}
128
129/// Converts any type that implements `Display` to a Python `RuntimeError`.
130///
131/// # Errors
132///
133/// Returns a Python error with the error string.
134pub fn to_pyruntime_err(e: impl Display) -> PyErr {
135 PyRuntimeError::new_err(e.to_string())
136}
137
138/// Return a value indicating whether the `obj` is a `PyCapsule`.
139///
140/// Parameters
141/// ----------
142/// obj : Any
143/// The object to check.
144///
145/// Returns
146/// -------
147/// bool
148#[gen_stub_pyfunction(module = "nautilus_trader.core")]
149#[pyfunction(name = "is_pycapsule")]
150#[allow(
151 clippy::needless_pass_by_value,
152 reason = "Python FFI requires owned types"
153)]
154#[allow(unsafe_code)]
155fn py_is_pycapsule(obj: Py<PyAny>) -> bool {
156 // SAFETY: obj.as_ptr() returns a valid Python object pointer
157 unsafe {
158 // PyCapsule_CheckExact checks if the object is exactly a PyCapsule
159 pyo3::ffi::PyCapsule_CheckExact(obj.as_ptr()) != 0
160 }
161}
162
163/// Loaded as `nautilus_pyo3.core`.
164///
165/// # Errors
166///
167/// Returns a `PyErr` if registering any module components fails.
168#[pymodule]
169#[rustfmt::skip]
170pub fn core(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
171 m.add(stringify!(NAUTILUS_VERSION), NAUTILUS_VERSION)?;
172 m.add(stringify!(NAUTILUS_USER_AGENT), NAUTILUS_USER_AGENT)?;
173 m.add(stringify!(MILLISECONDS_IN_SECOND), MILLISECONDS_IN_SECOND)?;
174 m.add(stringify!(NANOSECONDS_IN_SECOND), NANOSECONDS_IN_SECOND)?;
175 m.add(stringify!(NANOSECONDS_IN_MILLISECOND), NANOSECONDS_IN_MILLISECOND)?;
176 m.add(stringify!(NANOSECONDS_IN_MICROSECOND), NANOSECONDS_IN_MICROSECOND)?;
177 m.add_class::<UUID4>()?;
178 m.add_function(wrap_pyfunction!(py_is_pycapsule, m)?)?;
179 m.add_function(wrap_pyfunction!(casing::py_convert_to_snake_case, m)?)?;
180 m.add_function(wrap_pyfunction!(string::py_mask_api_key, m)?)?;
181 m.add_function(wrap_pyfunction!(datetime::py_secs_to_nanos, m)?)?;
182 m.add_function(wrap_pyfunction!(datetime::py_secs_to_millis, m)?)?;
183 m.add_function(wrap_pyfunction!(datetime::py_millis_to_nanos, m)?)?;
184 m.add_function(wrap_pyfunction!(datetime::py_micros_to_nanos, m)?)?;
185 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_secs, m)?)?;
186 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_millis, m)?)?;
187 m.add_function(wrap_pyfunction!(datetime::py_nanos_to_micros, m)?)?;
188 m.add_function(wrap_pyfunction!(datetime::py_unix_nanos_to_iso8601, m)?)?;
189 m.add_function(wrap_pyfunction!(datetime::py_last_weekday_nanos, m)?)?;
190 m.add_function(wrap_pyfunction!(datetime::py_is_within_last_24_hours, m)?)?;
191 Ok(())
192}