nautilus_infrastructure/redis/
mod.rs1pub mod cache;
19pub mod msgbus;
20pub mod queries;
21
22mod stream_fields;
23
24use std::{fmt::Write as _, time::Duration};
25
26use nautilus_common::{logging::log_task_awaiting, msgbus::MessageBusConfig};
27use nautilus_core::{UUID4, string::semver::SemVer};
28use nautilus_model::identifiers::TraderId;
29use redis::RedisError;
30
31const REDIS_MIN_VERSION: &str = "6.2.0";
32const REDIS_DELIMITER: char = ':';
33const REDIS_INDEX_PATTERN: &str = ":index:";
34const REDIS_XTRIM: &str = "XTRIM";
35const REDIS_MINID: &str = "MINID";
36const REDIS_FLUSHDB: &str = "FLUSHDB";
37
38pub(crate) fn get_index_key(key: &str) -> anyhow::Result<&str> {
43 if let Some(pos) = key.find(REDIS_INDEX_PATTERN) {
44 return Ok(&key[pos + 1..]);
45 }
46
47 if key.starts_with("index:") {
48 return Ok(key);
49 }
50
51 anyhow::bail!("Invalid index key format: {key}")
52}
53
54async fn await_handle(handle: Option<tokio::task::JoinHandle<()>>, task_name: &str) {
55 if let Some(handle) = handle {
56 log_task_awaiting(task_name);
57
58 let timeout = Duration::from_secs(2);
59 match tokio::time::timeout(timeout, handle).await {
60 Ok(result) => {
61 if let Err(e) = result {
62 log::error!("Error awaiting task '{task_name}': {e:?}");
63 }
64 }
65 Err(_) => {
66 log::warn!("Timeout {timeout:?} awaiting task '{task_name}'");
67 }
68 }
69 }
70}
71
72pub trait RedisConnectionConfig {
74 fn host(&self) -> Option<&str>;
75 fn port(&self) -> Option<u16>;
76 fn username(&self) -> Option<&str>;
77 fn password(&self) -> Option<&str>;
78 fn ssl(&self) -> bool;
79 fn connection_timeout(&self) -> u16;
80 fn response_timeout(&self) -> u16;
81 fn number_of_retries(&self) -> usize;
82 fn exponent_base(&self) -> u64;
83 fn max_delay(&self) -> u64;
84 fn factor(&self) -> u64;
85}
86
87#[must_use]
103pub fn get_redis_url(config: &impl RedisConnectionConfig) -> (String, String) {
104 let host = config.host().unwrap_or("127.0.0.1");
105 let port = config.port().unwrap_or(6379);
106 let username = config.username().unwrap_or_default();
107 let password = config.password().unwrap_or_default();
108 let ssl = config.ssl();
109
110 let redact_pw = |pw: &str| {
112 if pw.len() > 4 {
113 format!("{}...{}", &pw[..2], &pw[pw.len() - 2..])
114 } else {
115 pw.to_owned()
116 }
117 };
118
119 let (auth, auth_redacted) = match (username.is_empty(), password.is_empty()) {
121 (false, false) => (
123 format!("{username}:{password}@"),
124 format!("{username}:{}@", redact_pw(password)),
125 ),
126 (true, false) => (
128 format!(":{password}@"),
129 format!(":{}@", redact_pw(password)),
130 ),
131 (false, true) => panic!(
133 "Redis config error: username supplied without password. \
134 Either supply a password or omit the username."
135 ),
136 (true, true) => (String::new(), String::new()),
138 };
139
140 let scheme = if ssl { "rediss" } else { "redis" };
141
142 let url = format!("{scheme}://{auth}{host}:{port}");
143 let redacted_url = format!("{scheme}://{auth_redacted}{host}:{port}");
144
145 (url, redacted_url)
146}
147
148pub async fn create_redis_connection(
163 con_name: &str,
164 config: &impl RedisConnectionConfig,
165) -> anyhow::Result<redis::aio::ConnectionManager> {
166 log::debug!("Creating {con_name} redis connection");
167 let (redis_url, redacted_url) = get_redis_url(config);
168 log::debug!("Connecting to {redacted_url}");
169
170 let connection_timeout = Duration::from_secs(u64::from(config.connection_timeout()));
171 let response_timeout = Duration::from_secs(u64::from(config.response_timeout()));
172 let number_of_retries = config.number_of_retries();
173 #[expect(
174 clippy::cast_precision_loss,
175 reason = "redis connection manager API accepts exponent base as f32"
176 )]
177 let exponent_base = config.exponent_base() as f32;
178
179 let min_delay = Duration::from_millis(config.factor());
181 let max_delay = Duration::from_secs(config.max_delay());
182
183 let client = redis::Client::open(redis_url)?;
184
185 let connection_manager_config = redis::aio::ConnectionManagerConfig::new()
186 .set_exponent_base(exponent_base)
187 .set_number_of_retries(number_of_retries)
188 .set_response_timeout(Some(response_timeout))
189 .set_connection_timeout(Some(connection_timeout))
190 .set_min_delay(min_delay)
191 .set_max_delay(max_delay);
192
193 let mut con = client
194 .get_connection_manager_with_config(connection_manager_config)
195 .await?;
196
197 let version = get_redis_version(&mut con).await?;
198 let min_version = SemVer::parse(REDIS_MIN_VERSION)?;
199 let con_msg = format!("Connected to redis v{version}");
200
201 if version >= min_version {
202 log::info!("{con_msg}");
203 } else {
204 log::error!("{con_msg}, but minimum supported version is {REDIS_MIN_VERSION}");
205 }
206
207 Ok(con)
208}
209
210pub async fn flush_redis(
216 con: &mut redis::aio::ConnectionManager,
217) -> anyhow::Result<(), RedisError> {
218 redis::cmd(REDIS_FLUSHDB).exec_async(con).await
219}
220
221#[must_use]
223pub fn get_stream_key(
224 trader_id: TraderId,
225 instance_id: UUID4,
226 config: &MessageBusConfig,
227) -> String {
228 let mut stream_key = String::new();
229
230 if config.use_trader_prefix {
231 stream_key.push_str("trader-");
232 }
233
234 if config.use_trader_id {
235 stream_key.push_str(trader_id.as_str());
236 stream_key.push(REDIS_DELIMITER);
237 }
238
239 if config.use_instance_id {
240 write!(stream_key, "{instance_id}").expect("writing to String cannot fail");
241 stream_key.push(REDIS_DELIMITER);
242 }
243
244 stream_key.push_str(&config.streams_prefix);
245 stream_key
246}
247
248async fn get_redis_version(conn: &mut redis::aio::ConnectionManager) -> anyhow::Result<SemVer> {
249 let info: String = redis::cmd("INFO").query_async(conn).await?;
250 let Some(version_str) = info.lines().find_map(|line| {
251 if line.starts_with("redis_version:") {
252 line.split(':').nth(1).map(|s| s.trim().to_string())
253 } else {
254 None
255 }
256 }) else {
257 anyhow::bail!("Redis version not available");
258 };
259
260 SemVer::parse(&version_str)
261}
262
263#[cfg(test)]
264mod tests {
265 use rstest::rstest;
266 use serde_json::json;
267
268 use super::*;
269 use crate::redis::cache::RedisCacheConfig;
270
271 #[rstest]
272 fn test_get_redis_url_default_values() {
273 let config: RedisCacheConfig = serde_json::from_value(json!({})).unwrap();
274 let (url, redacted_url) = get_redis_url(&config);
275 assert_eq!(url, "redis://127.0.0.1:6379");
276 assert_eq!(redacted_url, "redis://127.0.0.1:6379");
277 }
278
279 #[rstest]
280 fn test_get_redis_url_password_only() {
281 let config_json = json!({
283 "host": "example.com",
284 "port": 6380,
285 "password": "secretpw", });
287 let config: RedisCacheConfig = serde_json::from_value(config_json).unwrap();
288 let (url, redacted_url) = get_redis_url(&config);
289 assert_eq!(url, "redis://:secretpw@example.com:6380");
290 assert_eq!(redacted_url, "redis://:se...pw@example.com:6380");
291 }
292
293 #[rstest]
294 fn test_get_redis_url_full_config_with_ssl() {
295 let config_json = json!({
296 "host": "example.com",
297 "port": 6380,
298 "username": "user",
299 "password": "pass",
300 "ssl": true,
301 });
302 let config: RedisCacheConfig = serde_json::from_value(config_json).unwrap();
303 let (url, redacted_url) = get_redis_url(&config);
304 assert_eq!(url, "rediss://user:pass@example.com:6380");
305 assert_eq!(redacted_url, "rediss://user:pass@example.com:6380");
306 }
307
308 #[rstest]
309 fn test_get_redis_url_full_config_without_ssl() {
310 let config_json = json!({
311 "host": "example.com",
312 "port": 6380,
313 "username": "username",
314 "password": "password",
315 "ssl": false,
316 });
317 let config: RedisCacheConfig = serde_json::from_value(config_json).unwrap();
318 let (url, redacted_url) = get_redis_url(&config);
319 assert_eq!(url, "redis://username:password@example.com:6380");
320 assert_eq!(redacted_url, "redis://username:pa...rd@example.com:6380");
321 }
322
323 #[rstest]
324 fn test_get_redis_url_missing_username_and_password() {
325 let config_json = json!({
326 "host": "example.com",
327 "port": 6380,
328 "ssl": false,
329 });
330 let config: RedisCacheConfig = serde_json::from_value(config_json).unwrap();
331 let (url, redacted_url) = get_redis_url(&config);
332 assert_eq!(url, "redis://example.com:6380");
333 assert_eq!(redacted_url, "redis://example.com:6380");
334 }
335
336 #[rstest]
337 fn test_get_redis_url_ssl_default_false() {
338 let config_json = json!({
339 "host": "example.com",
340 "port": 6380,
341 "username": "username",
342 "password": "password",
343 });
345 let config: RedisCacheConfig = serde_json::from_value(config_json).unwrap();
346 let (url, redacted_url) = get_redis_url(&config);
347 assert_eq!(url, "redis://username:password@example.com:6380");
348 assert_eq!(redacted_url, "redis://username:pa...rd@example.com:6380");
349 }
350
351 #[rstest]
352 fn test_get_stream_key_with_trader_prefix_and_instance_id() {
353 let trader_id = TraderId::from("tester-123");
354 let instance_id = UUID4::new();
355 let config = MessageBusConfig {
356 use_instance_id: true,
357 ..Default::default()
358 };
359
360 let key = get_stream_key(trader_id, instance_id, &config);
361 assert_eq!(key, format!("trader-tester-123:{instance_id}:stream"));
362 }
363
364 #[rstest]
365 fn test_get_stream_key_without_trader_prefix_or_instance_id() {
366 let trader_id = TraderId::from("tester-123");
367 let instance_id = UUID4::new();
368 let config = MessageBusConfig {
369 use_trader_prefix: false,
370 use_trader_id: false,
371 ..Default::default()
372 };
373
374 let key = get_stream_key(trader_id, instance_id, &config);
375 assert_eq!(key, "stream".to_string());
376 }
377
378 #[rstest]
379 fn test_get_index_key_without_prefix() {
380 let key = "index:order_position";
381 assert_eq!(get_index_key(key).unwrap(), "index:order_position");
382 }
383
384 #[rstest]
385 fn test_get_index_key_with_trader_prefix() {
386 let key = "trader-tester-123:index:order_position";
387 assert_eq!(get_index_key(key).unwrap(), "index:order_position");
388 }
389
390 #[rstest]
391 fn test_get_index_key_with_instance_id() {
392 let key = "trader-tester-123:abc-uuid-123:index:order_position";
393 assert_eq!(get_index_key(key).unwrap(), "index:order_position");
394 }
395
396 #[rstest]
397 fn test_get_index_key_invalid() {
398 let key = "no_index_pattern";
399 assert!(get_index_key(key).is_err());
400 }
401}