use super::DbContext; use r2d2::{Pool, PooledConnection}; use redis::Client; impl DbContext { pub(super) async fn get_redis_connection(&mut self) -> Option> { if let Some(pool) = self.redis_pool.as_ref() { match pool.get() { Ok(x) => return Some(x), Err(e) => { log::error!("Failed to grab redis connection: {e}"); } } } // Reset redis_pool if we cannot grab a connection self.redis_pool = None; self.redis_connect().await; let pool = match self.redis_pool.as_ref() { Some(x) => x, None => return None, }; let conn = match pool.get() { Ok(x) => x, Err(e) => { log::error!("Failed to grab redis connection: {e}"); return None; } }; return Some(conn); } pub(super) async fn redis_connect(&mut self) -> () { let db_url = match std::env::var("REDIS_URL") { Ok(url) => url, Err(e) => { panic!( "REDIS_URL environment variable is missing, cannot connect to database: {e}" ); } }; let client = match Client::open(db_url) { Ok(x) => x, Err(e) => { log::error!("Failed to connect to database at REDIS_URL: {e}"); log::warn!( "Requests requiring redis will request a connection retry, but may fail." ); return; } }; let pool = match Pool::builder().build(client) { Ok(x) => x, Err(e) => { log::error!("Failed initialize pool of redis connections: {e}"); log::warn!( "Requests requiring redis will request a connection retry, but may fail." ); return; } }; self.redis_pool = Some(pool); log::info!("Successfully connected to Redis instance"); } }