actix_extended_session/storage/
redis_rs.rs

1use std::{convert::TryInto, sync::Arc};
2
3use actix_web::cookie::time::Duration;
4use anyhow::{Context, Error};
5use redis::{aio::ConnectionManager, AsyncCommands, Cmd, FromRedisValue, RedisResult, Value};
6
7use super::SessionKey;
8use crate::storage::{
9    interface::{LoadError, SaveError, SessionState, UpdateError},
10    utils::generate_session_key,
11    SessionStore,
12};
13
14/// Use Redis as session storage backend.
15///
16/// # TLS support
17/// Add the `redis-rs-tls-session` feature flag to enable TLS support. You can then establish a TLS
18/// connection to Redis using the `rediss://` URL scheme:
19///
20/// # Implementation notes
21/// `RedisSessionStore` leverages [`redis-rs`] as Redis client.
22///
23/// [`redis-rs`]: https://github.com/mitsuhiko/redis-rs
24#[derive(Clone)]
25pub struct RedisSessionStore {
26    configuration: CacheConfiguration,
27    client: ConnectionManager,
28}
29
30#[derive(Clone)]
31struct CacheConfiguration {
32    cache_keygen: Arc<dyn Fn(&str) -> String + Send + Sync>,
33}
34
35impl Default for CacheConfiguration {
36    fn default() -> Self {
37        Self {
38            cache_keygen: Arc::new(str::to_owned),
39        }
40    }
41}
42
43impl RedisSessionStore {
44    /// A fluent API to configure [`RedisSessionStore`].
45    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
46    /// connection string for Redis.
47    pub fn builder<S: Into<String>>(connection_string: S) -> RedisSessionStoreBuilder {
48        RedisSessionStoreBuilder {
49            configuration: CacheConfiguration::default(),
50            connection_string: connection_string.into(),
51        }
52    }
53
54    /// Create a new instance of [`RedisSessionStore`] using the default configuration.
55    /// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
56    /// connection string for Redis.
57    pub async fn new<S: Into<String>>(
58        connection_string: S,
59    ) -> Result<RedisSessionStore, anyhow::Error> {
60        Self::builder(connection_string).build().await
61    }
62}
63
64/// A fluent builder to construct a [`RedisSessionStore`] instance with custom configuration
65/// parameters.
66///
67/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
68#[must_use]
69pub struct RedisSessionStoreBuilder {
70    connection_string: String,
71    configuration: CacheConfiguration,
72}
73
74impl RedisSessionStoreBuilder {
75    /// Set a custom cache key generation strategy, expecting a session key as input.
76    pub fn cache_keygen<F>(mut self, keygen: F) -> Self
77    where
78        F: Fn(&str) -> String + 'static + Send + Sync,
79    {
80        self.configuration.cache_keygen = Arc::new(keygen);
81        self
82    }
83
84    /// Finalise the builder and return a [`RedisActorSessionStore`] instance.
85    ///
86    /// [`RedisActorSessionStore`]: crate::storage::RedisActorSessionStore
87    pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> {
88        let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?;
89        Ok(RedisSessionStore {
90            configuration: self.configuration,
91            client,
92        })
93    }
94}
95
96#[async_trait::async_trait(?Send)]
97impl SessionStore for RedisSessionStore {
98    async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
99        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
100
101        let value: Option<String> = self
102            .execute_command(redis::cmd("GET").arg(&[&cache_key]))
103            .await
104            .map_err(Into::into)
105            .map_err(LoadError::Other)?;
106
107        match value {
108            None => Ok(None),
109            Some(value) => Ok(serde_json::from_str(&value)
110                .map_err(Into::into)
111                .map_err(LoadError::Deserialization)?),
112        }
113    }
114
115    async fn save(
116        &self,
117        session_state: SessionState,
118        ttl: &Duration,
119    ) -> Result<SessionKey, SaveError> {
120        let user_id = session_state.get("user_id");
121        let body = serde_json::to_string(&session_state)
122            .map_err(Into::into)
123            .map_err(SaveError::Serialization)?;
124        let session_key = generate_session_key(user_id.and_then(|value| Some(value.to_string())));
125        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
126
127        self.execute_command(redis::cmd("SET").arg(&[
128            &cache_key,
129            &body,
130            "NX", // NX: only set the key if it does not already exist
131            "EX", // EX: set expiry
132            &format!("{}", ttl.whole_seconds()),
133        ]))
134        .await
135        .map_err(Into::into)
136        .map_err(SaveError::Other)?;
137
138        Ok(session_key)
139    }
140
141    async fn update(
142        &self,
143        session_key: SessionKey,
144        session_state: SessionState,
145        ttl: &Duration,
146    ) -> Result<SessionKey, UpdateError> {
147        let body = serde_json::to_string(&session_state)
148            .map_err(Into::into)
149            .map_err(UpdateError::Serialization)?;
150
151        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
152
153        let v: redis::Value = self
154            .execute_command(redis::cmd("SET").arg(&[
155                &cache_key,
156                &body,
157                "XX", // XX: Only set the key if it already exist.
158                "EX", // EX: set expiry
159                &format!("{}", ttl.whole_seconds()),
160            ]))
161            .await
162            .map_err(Into::into)
163            .map_err(UpdateError::Other)?;
164
165        match v {
166            Value::Nil => {
167                // The SET operation was not performed because the XX condition was not verified.
168                // This can happen if the session state expired between the load operation and the
169                // update operation. Unlucky, to say the least. We fall back to the `save` routine
170                // to ensure that the new key is unique.
171                self.save(session_state, ttl)
172                    .await
173                    .map_err(|err| match err {
174                        SaveError::Serialization(err) => UpdateError::Serialization(err),
175                        SaveError::Other(err) => UpdateError::Other(err),
176                    })
177            }
178            Value::Int(_) | Value::Okay | Value::Status(_) => Ok(session_key),
179            val => Err(UpdateError::Other(anyhow::anyhow!(
180                "Failed to update session state. {:?}",
181                val
182            ))),
183        }
184    }
185
186    async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
187        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
188
189        self.client
190            .clone()
191            .expire(
192                &cache_key,
193                ttl.whole_seconds().try_into().context(
194                    "Failed to convert the state TTL into the number of whole seconds remaining",
195                )?,
196            )
197            .await?;
198        Ok(())
199    }
200
201    async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
202        let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
203        self.execute_command(redis::cmd("DEL").arg(&[&cache_key]))
204            .await
205            .map_err(Into::into)
206            .map_err(UpdateError::Other)?;
207
208        Ok(())
209    }
210}
211
212impl RedisSessionStore {
213    /// Execute Redis command and retry once in certain cases.
214    ///
215    /// `ConnectionManager` automatically reconnects when it encounters an error talking to Redis.
216    /// The request that bumped into the error, though, fails.
217    ///
218    /// This is generally OK, but there is an unpleasant edge case: Redis client timeouts. The
219    /// server is configured to drop connections who have been active longer than a pre-determined
220    /// threshold. `redis-rs` does not proactively detect that the connection has been dropped - you
221    /// only find out when you try to use it.
222    ///
223    /// This helper method catches this case (`.is_connection_dropped`) to execute a retry. The
224    /// retry will be executed on a fresh connection, therefore it is likely to succeed (or fail for
225    /// a different more meaningful reason).
226    #[allow(clippy::needless_pass_by_ref_mut)]
227    async fn execute_command<T: FromRedisValue>(&self, cmd: &mut Cmd) -> RedisResult<T> {
228        let mut can_retry = true;
229
230        loop {
231            match cmd.query_async(&mut self.client.clone()).await {
232                Ok(value) => return Ok(value),
233                Err(err) => {
234                    if can_retry && err.is_connection_dropped() {
235                        tracing::debug!(
236                            "Connection dropped while trying to talk to Redis. Retrying."
237                        );
238
239                        // Retry at most once
240                        can_retry = false;
241
242                        continue;
243                    } else {
244                        return Err(err);
245                    }
246                }
247            }
248        }
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use actix_web::cookie::time;
255    use redis::AsyncCommands;
256    use serde_json::Map;
257
258    use super::*;
259    use crate::test_helpers::acceptance_test_suite;
260
261    async fn redis_store() -> RedisSessionStore {
262        RedisSessionStore::new("redis://127.0.0.1:7001")
263            .await
264            .unwrap()
265    }
266
267    #[actix_web::test]
268    async fn test_session_workflow() {
269        let redis_store = redis_store().await;
270        acceptance_test_suite(move || redis_store.clone(), true).await;
271    }
272
273    #[actix_web::test]
274    async fn loading_a_missing_session_returns_none() {
275        let store = redis_store().await;
276        let session_key = generate_session_key(None);
277        assert!(store.load(&session_key).await.unwrap().is_none());
278    }
279
280    #[actix_web::test]
281    async fn loading_an_invalid_session_state_returns_deserialization_error() {
282        let store = redis_store().await;
283        let session_key = generate_session_key(None);
284        store
285            .client
286            .clone()
287            .set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
288            .await
289            .unwrap();
290        assert!(matches!(
291            store.load(&session_key).await.unwrap_err(),
292            LoadError::Deserialization(_),
293        ));
294    }
295
296    #[actix_web::test]
297    async fn updating_of_an_expired_state_is_handled_gracefully() {
298        let store = redis_store().await;
299        let session_key = generate_session_key(None);
300        let initial_session_key = session_key.as_ref().to_owned();
301        let updated_session_key = store
302            .update(session_key, Map::new(), &time::Duration::seconds(1))
303            .await
304            .unwrap();
305        assert_ne!(initial_session_key, updated_session_key.as_ref());
306    }
307}