Skip to main content

nautilus_infrastructure/python/
mod.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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//! Python bindings from [PyO3](https://pyo3.rs).
17
18#[cfg(feature = "redis")]
19pub mod redis;
20
21#[cfg(feature = "postgres")]
22pub mod sql;
23
24use pyo3::{prelude::*, pymodule};
25
26/// Python module initializer for the `infrastructure` package.
27///
28/// # Errors
29///
30/// Returns an error if the module initialization fails, e.g., when adding classes to the module.
31#[pymodule]
32pub fn infrastructure(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
33    #[cfg(not(any(feature = "redis", feature = "postgres")))]
34    let _ = m;
35
36    #[cfg(feature = "redis")]
37    m.add_class::<crate::redis::cache::RedisCacheConfig>()?;
38    #[cfg(feature = "redis")]
39    m.add_class::<redis::msgbus::PyRedisMessageBusFactory>()?;
40    #[cfg(feature = "redis")]
41    m.add_class::<crate::redis::msgbus::RedisMessageBusConfig>()?;
42    #[cfg(feature = "redis")]
43    redis::msgbus::register_redis_msgbus_factory()?;
44    #[cfg(feature = "redis")]
45    redis::cache::register_redis_cache_database_factory()?;
46    #[cfg(feature = "postgres")]
47    m.add_class::<crate::sql::cache::PostgresCacheConfig>()?;
48    #[cfg(feature = "postgres")]
49    m.add_class::<crate::sql::pg::PostgresConnectOptions>()?;
50    #[cfg(feature = "postgres")]
51    sql::cache::register_postgres_cache_database_factory()?;
52    Ok(())
53}
54
55#[cfg(all(test, any(feature = "redis", feature = "postgres")))]
56mod tests {
57    use nautilus_common::python::cache::get_global_cache_database_factory_registry;
58    #[cfg(feature = "redis")]
59    use nautilus_common::python::msgbus::get_global_msgbus_factory_registry;
60    use pyo3::PyRef;
61    use rstest::rstest;
62
63    use super::*;
64
65    #[cfg(feature = "redis")]
66    #[rstest]
67    fn test_infrastructure_module_extracts_redis_cache_database_factory() {
68        Python::initialize();
69        Python::attach(|py| {
70            let module = PyModule::new(py, "infrastructure").unwrap();
71
72            infrastructure(py, &module).unwrap();
73
74            assert!(module.getattr("RedisCacheDatabase").is_err());
75
76            let config = module
77                .getattr("RedisCacheConfig")
78                .unwrap()
79                .call1((
80                    "redis.example.com",
81                    6380,
82                    "user",
83                    "secret",
84                    true,
85                    7,
86                    8,
87                    9,
88                    3,
89                    10,
90                    4,
91                ))
92                .unwrap();
93            {
94                let config = config
95                    .extract::<PyRef<crate::redis::cache::RedisCacheConfig>>()
96                    .unwrap();
97
98                assert_eq!(config.host.as_deref(), Some("redis.example.com"));
99                assert_eq!(config.port, Some(6380));
100                assert_eq!(config.username.as_deref(), Some("user"));
101                assert_eq!(config.password.as_deref(), Some("secret"));
102                assert!(config.ssl);
103                assert_eq!(config.connection_timeout, 7);
104                assert_eq!(config.response_timeout, 8);
105                assert_eq!(config.number_of_retries, 9);
106                assert_eq!(config.exponent_base, 3);
107                assert_eq!(config.max_delay, 10);
108                assert_eq!(config.factor, 4);
109            }
110            let factory = get_global_cache_database_factory_registry()
111                .extract(py, config.unbind())
112                .unwrap();
113            let debug = format!("{factory:?}");
114
115            assert!(debug.contains("redis.example.com"));
116            assert!(debug.contains("password: Some(\"***\")"));
117            assert!(!debug.contains("secret"));
118        });
119    }
120
121    #[cfg(feature = "postgres")]
122    #[rstest]
123    fn test_infrastructure_module_extracts_postgres_cache_database_factory() {
124        Python::initialize();
125        Python::attach(|py| {
126            let module = PyModule::new(py, "infrastructure").unwrap();
127
128            infrastructure(py, &module).unwrap();
129
130            assert!(module.getattr("PostgresCacheDatabase").is_err());
131
132            let config = module
133                .getattr("PostgresCacheConfig")
134                .unwrap()
135                .call1(("postgres.example.com", 5433, "user", "secret", "nautilus"))
136                .unwrap();
137            {
138                let config = config
139                    .extract::<PyRef<crate::sql::cache::PostgresCacheConfig>>()
140                    .unwrap();
141
142                assert_eq!(config.host.as_deref(), Some("postgres.example.com"));
143                assert_eq!(config.port, Some(5433));
144                assert_eq!(config.username.as_deref(), Some("user"));
145                assert_eq!(config.password.as_deref(), Some("secret"));
146                assert_eq!(config.database.as_deref(), Some("nautilus"));
147            }
148            let factory = get_global_cache_database_factory_registry()
149                .extract(py, config.unbind())
150                .unwrap();
151            let debug = format!("{factory:?}");
152
153            assert!(debug.contains("postgres.example.com"));
154            assert!(debug.contains("password: Some(\"***\")"));
155            assert!(!debug.contains("secret"));
156        });
157    }
158
159    #[cfg(feature = "redis")]
160    #[rstest]
161    fn test_infrastructure_module_exports_redis_message_bus_types() {
162        Python::initialize();
163        Python::attach(|py| {
164            let module = PyModule::new(py, "infrastructure").unwrap();
165
166            infrastructure(py, &module).unwrap();
167
168            assert!(module.getattr("RedisMessageBusBacking").is_err());
169            assert!(module.getattr("RedisMessageBusConfig").is_ok());
170            assert!(module.getattr("RedisMessageBusFactory").is_ok());
171
172            let config = module
173                .getattr("RedisMessageBusConfig")
174                .unwrap()
175                .call1((
176                    "redis.example.com",
177                    6380,
178                    "user",
179                    "secret",
180                    true,
181                    7,
182                    8,
183                    9,
184                    3,
185                    10,
186                    4,
187                ))
188                .unwrap();
189            {
190                let config = config
191                    .extract::<PyRef<crate::redis::msgbus::RedisMessageBusConfig>>()
192                    .unwrap();
193
194                assert_eq!(config.host.as_deref(), Some("redis.example.com"));
195                assert_eq!(config.port, Some(6380));
196                assert_eq!(config.username.as_deref(), Some("user"));
197                assert_eq!(config.password.as_deref(), Some("secret"));
198                assert!(config.ssl);
199                assert_eq!(config.connection_timeout, 7);
200                assert_eq!(config.response_timeout, 8);
201                assert_eq!(config.number_of_retries, 9);
202                assert_eq!(config.exponent_base, 3);
203                assert_eq!(config.max_delay, 10);
204                assert_eq!(config.factor, 4);
205            }
206            let direct_factory = get_global_msgbus_factory_registry()
207                .extract(py, config.unbind())
208                .unwrap();
209            let debug = format!("{direct_factory:?}");
210
211            assert!(debug.contains("redis.example.com"));
212            assert!(debug.contains("password: Some(\"***\")"));
213            assert!(!debug.contains("secret"));
214
215            let config = module
216                .getattr("RedisMessageBusConfig")
217                .unwrap()
218                .call1(("redis.example.com", 6380, "user", "secret"))
219                .unwrap();
220            let factory = module
221                .getattr("RedisMessageBusFactory")
222                .unwrap()
223                .call1((config,))
224                .unwrap()
225                .unbind();
226            let compatibility_factory = get_global_msgbus_factory_registry()
227                .extract(py, factory)
228                .unwrap();
229            let debug = format!("{compatibility_factory:?}");
230
231            assert!(debug.contains("redis.example.com"));
232            assert!(debug.contains("password: Some(\"***\")"));
233            assert!(!debug.contains("secret"));
234
235            let second_module = PyModule::new(py, "infrastructure").unwrap();
236            infrastructure(py, &second_module).unwrap();
237            assert!(second_module.getattr("RedisMessageBusConfig").is_ok());
238            assert!(second_module.getattr("RedisMessageBusFactory").is_ok());
239        });
240    }
241}