LCOV - code coverage report
Current view: top level - proxy/src/redis - connection_with_credentials_provider.rs (source / functions) Coverage Total Hit
Test: f081ec316c96fa98335efd15ef501745aa4f015d.info Lines: 0.0 % 156 0
Test Date: 2024-06-25 15:11:17 Functions: 0.0 % 29 0

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

Generated by: LCOV version 2.1-beta