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 : pub async fn connect(&mut self) -> anyhow::Result<()> {
81 0 : let _guard = self.mutex.lock().await;
82 0 : if let Some(con) = self.con.as_mut() {
83 0 : match redis::cmd("PING").query_async(con).await {
84 : Ok(()) => {
85 0 : return Ok(());
86 : }
87 0 : Err(e) => {
88 0 : error!("Error during PING: {e:?}");
89 : }
90 : }
91 : } else {
92 0 : info!("Connection is not established");
93 : }
94 0 : info!("Establishing a new connection...");
95 0 : self.con = None;
96 0 : if let Some(f) = self.refresh_token_task.take() {
97 0 : f.abort()
98 0 : }
99 0 : let con = self
100 0 : .get_client()
101 0 : .await?
102 0 : .get_multiplexed_tokio_connection()
103 0 : .await?;
104 0 : if let Credentials::Dynamic(credentials_provider, _) = &self.credentials {
105 0 : let credentials_provider = credentials_provider.clone();
106 0 : let con2 = con.clone();
107 0 : let f = tokio::spawn(async move {
108 0 : let _ = Self::keep_connection(con2, credentials_provider).await;
109 0 : });
110 0 : self.refresh_token_task = Some(f);
111 0 : }
112 0 : self.con = Some(con);
113 0 : Ok(())
114 0 : }
115 :
116 0 : async fn get_connection_info(&self) -> anyhow::Result<ConnectionInfo> {
117 0 : match &self.credentials {
118 0 : Credentials::Static(info) => Ok(info.clone()),
119 0 : Credentials::Dynamic(provider, addr) => {
120 0 : let (username, password) = provider.provide_credentials().await?;
121 0 : Ok(ConnectionInfo {
122 0 : addr: addr.clone(),
123 0 : redis: RedisConnectionInfo {
124 0 : db: 0,
125 0 : username: Some(username),
126 0 : password: Some(password.clone()),
127 0 : },
128 0 : })
129 : }
130 : }
131 0 : }
132 :
133 0 : async fn get_client(&self) -> anyhow::Result<redis::Client> {
134 0 : let client = redis::Client::open(self.get_connection_info().await?)?;
135 0 : Ok(client)
136 0 : }
137 :
138 : // PubSub does not support credentials refresh.
139 : // Requires manual reconnection every 12h.
140 0 : pub async fn get_async_pubsub(&self) -> anyhow::Result<redis::aio::PubSub> {
141 0 : Ok(self.get_client().await?.get_async_pubsub().await?)
142 0 : }
143 :
144 : // The connection lives for 12h.
145 : // It can be prolonged with sending `AUTH` commands with the refreshed token.
146 : // https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/auth-iam.html#auth-iam-limits
147 0 : async fn keep_connection(
148 0 : mut con: MultiplexedConnection,
149 0 : credentials_provider: Arc<CredentialsProvider>,
150 0 : ) -> anyhow::Result<()> {
151 : loop {
152 : // The connection lives for 12h, for the sanity check we refresh it every hour.
153 0 : tokio::time::sleep(Duration::from_secs(60 * 60)).await;
154 0 : match Self::refresh_token(&mut con, credentials_provider.clone()).await {
155 : Ok(()) => {
156 0 : info!("Token refreshed");
157 : }
158 0 : Err(e) => {
159 0 : error!("Error during token refresh: {e:?}");
160 : }
161 : }
162 : }
163 : }
164 0 : async fn refresh_token(
165 0 : con: &mut MultiplexedConnection,
166 0 : credentials_provider: Arc<CredentialsProvider>,
167 0 : ) -> anyhow::Result<()> {
168 0 : let (user, password) = credentials_provider.provide_credentials().await?;
169 0 : redis::cmd("AUTH")
170 0 : .arg(user)
171 0 : .arg(password)
172 0 : .query_async(con)
173 0 : .await?;
174 0 : Ok(())
175 0 : }
176 : /// Sends an already encoded (packed) command into the TCP socket and
177 : /// reads the single response from it.
178 0 : pub async fn send_packed_command(&mut self, cmd: &redis::Cmd) -> RedisResult<redis::Value> {
179 : // Clone connection to avoid having to lock the ArcSwap in write mode
180 0 : let con = self.con.as_mut().ok_or(redis::RedisError::from((
181 0 : redis::ErrorKind::IoError,
182 0 : "Connection not established",
183 0 : )))?;
184 0 : con.send_packed_command(cmd).await
185 0 : }
186 :
187 : /// Sends multiple already encoded (packed) command into the TCP socket
188 : /// and reads `count` responses from it. This is used to implement
189 : /// pipelining.
190 0 : pub async fn send_packed_commands(
191 0 : &mut self,
192 0 : cmd: &redis::Pipeline,
193 0 : offset: usize,
194 0 : count: usize,
195 0 : ) -> RedisResult<Vec<redis::Value>> {
196 : // Clone shared connection future to avoid having to lock the ArcSwap in write mode
197 0 : let con = self.con.as_mut().ok_or(redis::RedisError::from((
198 0 : redis::ErrorKind::IoError,
199 0 : "Connection not established",
200 0 : )))?;
201 0 : con.send_packed_commands(cmd, offset, count).await
202 0 : }
203 : }
204 :
205 : impl ConnectionLike for ConnectionWithCredentialsProvider {
206 0 : fn req_packed_command<'a>(
207 0 : &'a mut self,
208 0 : cmd: &'a redis::Cmd,
209 0 : ) -> redis::RedisFuture<'a, redis::Value> {
210 0 : (async move { self.send_packed_command(cmd).await }).boxed()
211 0 : }
212 :
213 0 : fn req_packed_commands<'a>(
214 0 : &'a mut self,
215 0 : cmd: &'a redis::Pipeline,
216 0 : offset: usize,
217 0 : count: usize,
218 0 : ) -> redis::RedisFuture<'a, Vec<redis::Value>> {
219 0 : (async move { self.send_packed_commands(cmd, offset, count).await }).boxed()
220 0 : }
221 :
222 0 : fn get_db(&self) -> i64 {
223 0 : 0
224 0 : }
225 : }
|