LCOV - code coverage report
Current view: top level - proxy/src/redis - connection_with_credentials_provider.rs (source / functions) Coverage Total Hit
Test: ac1e0b9bf1b4ead74961174b01ba016322d3f9a6.info Lines: 0.0 % 178 0
Test Date: 2025-07-08 09:16:10 Functions: 0.0 % 27 0

            Line data    Source code
       1              : use std::sync::Arc;
       2              : use std::sync::atomic::{AtomicBool, Ordering};
       3              : use std::time::Duration;
       4              : 
       5              : use futures::FutureExt;
       6              : use redis::aio::{ConnectionLike, MultiplexedConnection};
       7              : use redis::{ConnectionInfo, IntoConnectionInfo, RedisConnectionInfo, RedisResult};
       8              : use tokio::task::AbortHandle;
       9              : use tracing::{error, info, warn};
      10              : 
      11              : use super::elasticache::CredentialsProvider;
      12              : 
      13              : enum Credentials {
      14              :     Static(ConnectionInfo),
      15              :     Dynamic(Arc<CredentialsProvider>, redis::ConnectionAddr),
      16              : }
      17              : 
      18              : impl Clone for Credentials {
      19            0 :     fn clone(&self) -> Self {
      20            0 :         match self {
      21            0 :             Credentials::Static(info) => Credentials::Static(info.clone()),
      22            0 :             Credentials::Dynamic(provider, addr) => {
      23            0 :                 Credentials::Dynamic(Arc::clone(provider), addr.clone())
      24              :             }
      25              :         }
      26            0 :     }
      27              : }
      28              : 
      29              : /// A wrapper around `redis::MultiplexedConnection` that automatically refreshes the token.
      30              : /// Provides PubSub connection without credentials refresh.
      31              : pub struct ConnectionWithCredentialsProvider {
      32              :     credentials: Credentials,
      33              :     // TODO: with more load on the connection, we should consider using a connection pool
      34              :     con: Option<MultiplexedConnection>,
      35              :     refresh_token_task: Option<AbortHandle>,
      36              :     mutex: tokio::sync::Mutex<()>,
      37              :     credentials_refreshed: Arc<AtomicBool>,
      38              : }
      39              : 
      40              : impl Clone for ConnectionWithCredentialsProvider {
      41            0 :     fn clone(&self) -> Self {
      42            0 :         Self {
      43            0 :             credentials: self.credentials.clone(),
      44            0 :             con: None,
      45            0 :             refresh_token_task: None,
      46            0 :             mutex: tokio::sync::Mutex::new(()),
      47            0 :             credentials_refreshed: Arc::new(AtomicBool::new(false)),
      48            0 :         }
      49            0 :     }
      50              : }
      51              : 
      52              : impl ConnectionWithCredentialsProvider {
      53            0 :     pub fn new_with_credentials_provider(
      54            0 :         host: String,
      55            0 :         port: u16,
      56            0 :         credentials_provider: Arc<CredentialsProvider>,
      57            0 :     ) -> Self {
      58            0 :         Self {
      59            0 :             credentials: Credentials::Dynamic(
      60            0 :                 credentials_provider,
      61            0 :                 redis::ConnectionAddr::TcpTls {
      62            0 :                     host,
      63            0 :                     port,
      64            0 :                     insecure: false,
      65            0 :                     tls_params: None,
      66            0 :                 },
      67            0 :             ),
      68            0 :             con: None,
      69            0 :             refresh_token_task: None,
      70            0 :             mutex: tokio::sync::Mutex::new(()),
      71            0 :             credentials_refreshed: Arc::new(AtomicBool::new(false)),
      72            0 :         }
      73            0 :     }
      74              : 
      75            0 :     pub fn new_with_static_credentials<T: IntoConnectionInfo>(params: T) -> Self {
      76            0 :         Self {
      77            0 :             credentials: Credentials::Static(
      78            0 :                 params
      79            0 :                     .into_connection_info()
      80            0 :                     .expect("static configured redis credentials should be a valid format"),
      81            0 :             ),
      82            0 :             con: None,
      83            0 :             refresh_token_task: None,
      84            0 :             mutex: tokio::sync::Mutex::new(()),
      85            0 :             credentials_refreshed: Arc::new(AtomicBool::new(true)),
      86            0 :         }
      87            0 :     }
      88              : 
      89            0 :     async fn ping(con: &mut MultiplexedConnection) -> RedisResult<()> {
      90            0 :         redis::cmd("PING").query_async(con).await
      91            0 :     }
      92              : 
      93            0 :     pub(crate) fn credentials_refreshed(&self) -> bool {
      94            0 :         self.credentials_refreshed.load(Ordering::Relaxed)
      95            0 :     }
      96              : 
      97            0 :     pub(crate) async fn connect(&mut self) -> anyhow::Result<()> {
      98            0 :         let _guard = self.mutex.lock().await;
      99            0 :         if let Some(con) = self.con.as_mut() {
     100            0 :             match Self::ping(con).await {
     101              :                 Ok(()) => {
     102            0 :                     return Ok(());
     103              :                 }
     104            0 :                 Err(e) => {
     105            0 :                     warn!("Error during PING: {e:?}");
     106              :                 }
     107              :             }
     108              :         } else {
     109            0 :             info!("Connection is not established");
     110              :         }
     111            0 :         info!("Establishing a new connection...");
     112            0 :         self.con = None;
     113            0 :         if let Some(f) = self.refresh_token_task.take() {
     114            0 :             f.abort();
     115            0 :         }
     116            0 :         let mut con = self
     117            0 :             .get_client()
     118            0 :             .await?
     119            0 :             .get_multiplexed_tokio_connection()
     120            0 :             .await?;
     121            0 :         if let Credentials::Dynamic(credentials_provider, _) = &self.credentials {
     122            0 :             let credentials_provider = credentials_provider.clone();
     123            0 :             let con2 = con.clone();
     124            0 :             let credentials_refreshed = self.credentials_refreshed.clone();
     125            0 :             let f = tokio::spawn(Self::keep_connection(
     126            0 :                 con2,
     127            0 :                 credentials_provider,
     128            0 :                 credentials_refreshed,
     129            0 :             ));
     130            0 :             self.refresh_token_task = Some(f.abort_handle());
     131            0 :         }
     132            0 :         match Self::ping(&mut con).await {
     133              :             Ok(()) => {
     134            0 :                 info!("Connection succesfully established");
     135              :             }
     136            0 :             Err(e) => {
     137            0 :                 warn!("Connection is broken. Error during PING: {e:?}");
     138              :             }
     139              :         }
     140            0 :         self.con = Some(con);
     141            0 :         Ok(())
     142            0 :     }
     143              : 
     144            0 :     async fn get_connection_info(&self) -> anyhow::Result<ConnectionInfo> {
     145            0 :         match &self.credentials {
     146            0 :             Credentials::Static(info) => Ok(info.clone()),
     147            0 :             Credentials::Dynamic(provider, addr) => {
     148            0 :                 let (username, password) = provider.provide_credentials().await?;
     149            0 :                 Ok(ConnectionInfo {
     150            0 :                     addr: addr.clone(),
     151            0 :                     redis: RedisConnectionInfo {
     152            0 :                         db: 0,
     153            0 :                         username: Some(username),
     154            0 :                         password: Some(password.clone()),
     155            0 :                         // TODO: switch to RESP3 after testing new client version.
     156            0 :                         protocol: redis::ProtocolVersion::RESP2,
     157            0 :                     },
     158            0 :                 })
     159              :             }
     160              :         }
     161            0 :     }
     162              : 
     163            0 :     async fn get_client(&self) -> anyhow::Result<redis::Client> {
     164            0 :         let client = redis::Client::open(self.get_connection_info().await?)?;
     165            0 :         self.credentials_refreshed.store(true, Ordering::Relaxed);
     166            0 :         Ok(client)
     167            0 :     }
     168              : 
     169              :     // PubSub does not support credentials refresh.
     170              :     // Requires manual reconnection every 12h.
     171            0 :     pub(crate) async fn get_async_pubsub(&self) -> anyhow::Result<redis::aio::PubSub> {
     172            0 :         Ok(self.get_client().await?.get_async_pubsub().await?)
     173            0 :     }
     174              : 
     175              :     // The connection lives for 12h.
     176              :     // It can be prolonged with sending `AUTH` commands with the refreshed token.
     177              :     // https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/auth-iam.html#auth-iam-limits
     178            0 :     async fn keep_connection(
     179            0 :         mut con: MultiplexedConnection,
     180            0 :         credentials_provider: Arc<CredentialsProvider>,
     181            0 :         credentials_refreshed: Arc<AtomicBool>,
     182            0 :     ) -> ! {
     183              :         loop {
     184              :             // The connection lives for 12h, for the sanity check we refresh it every hour.
     185            0 :             tokio::time::sleep(Duration::from_secs(60 * 60)).await;
     186            0 :             match Self::refresh_token(&mut con, credentials_provider.clone()).await {
     187              :                 Ok(()) => {
     188            0 :                     info!("Token refreshed");
     189            0 :                     credentials_refreshed.store(true, Ordering::Relaxed);
     190              :                 }
     191            0 :                 Err(e) => {
     192            0 :                     error!("Error during token refresh: {e:?}");
     193            0 :                     credentials_refreshed.store(false, Ordering::Relaxed);
     194              :                 }
     195              :             }
     196              :         }
     197              :     }
     198            0 :     async fn refresh_token(
     199            0 :         con: &mut MultiplexedConnection,
     200            0 :         credentials_provider: Arc<CredentialsProvider>,
     201            0 :     ) -> anyhow::Result<()> {
     202            0 :         let (user, password) = credentials_provider.provide_credentials().await?;
     203            0 :         let _: () = redis::cmd("AUTH")
     204            0 :             .arg(user)
     205            0 :             .arg(password)
     206            0 :             .query_async(con)
     207            0 :             .await?;
     208            0 :         Ok(())
     209            0 :     }
     210              :     /// Sends an already encoded (packed) command into the TCP socket and
     211              :     /// reads the single response from it.
     212            0 :     pub(crate) async fn send_packed_command(
     213            0 :         &mut self,
     214            0 :         cmd: &redis::Cmd,
     215            0 :     ) -> RedisResult<redis::Value> {
     216              :         // Clone connection to avoid having to lock the ArcSwap in write mode
     217            0 :         let con = self.con.as_mut().ok_or(redis::RedisError::from((
     218            0 :             redis::ErrorKind::IoError,
     219            0 :             "Connection not established",
     220            0 :         )))?;
     221            0 :         con.send_packed_command(cmd).await
     222            0 :     }
     223              : 
     224              :     /// Sends multiple already encoded (packed) command into the TCP socket
     225              :     /// and reads `count` responses from it.  This is used to implement
     226              :     /// pipelining.
     227            0 :     pub(crate) async fn send_packed_commands(
     228            0 :         &mut self,
     229            0 :         cmd: &redis::Pipeline,
     230            0 :         offset: usize,
     231            0 :         count: usize,
     232            0 :     ) -> RedisResult<Vec<redis::Value>> {
     233              :         // Clone shared connection future to avoid having to lock the ArcSwap in write mode
     234            0 :         let con = self.con.as_mut().ok_or(redis::RedisError::from((
     235            0 :             redis::ErrorKind::IoError,
     236            0 :             "Connection not established",
     237            0 :         )))?;
     238            0 :         con.send_packed_commands(cmd, offset, count).await
     239            0 :     }
     240              : }
     241              : 
     242              : impl ConnectionLike for ConnectionWithCredentialsProvider {
     243            0 :     fn req_packed_command<'a>(
     244            0 :         &'a mut self,
     245            0 :         cmd: &'a redis::Cmd,
     246            0 :     ) -> redis::RedisFuture<'a, redis::Value> {
     247            0 :         self.send_packed_command(cmd).boxed()
     248            0 :     }
     249              : 
     250            0 :     fn req_packed_commands<'a>(
     251            0 :         &'a mut self,
     252            0 :         cmd: &'a redis::Pipeline,
     253            0 :         offset: usize,
     254            0 :         count: usize,
     255            0 :     ) -> redis::RedisFuture<'a, Vec<redis::Value>> {
     256            0 :         self.send_packed_commands(cmd, offset, count).boxed()
     257            0 :     }
     258              : 
     259            0 :     fn get_db(&self) -> i64 {
     260            0 :         self.con.as_ref().map_or(0, |c| c.get_db())
     261            0 :     }
     262              : }
        

Generated by: LCOV version 2.1-beta