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