Skip to main content

teloxide/dispatching/dialogue/storage/
redis_storage.rs

1use super::{initialize, DialogueKey, Serializer, Storage, StorageKeys};
2use deadpool_redis::{redis, CreatePoolError, PoolError, Runtime};
3use futures::future::BoxFuture;
4use redis::AsyncCommands;
5use serde::{de::DeserializeOwned, Serialize};
6use std::{
7    collections::HashSet,
8    convert::Infallible,
9    fmt::{Debug, Display},
10    sync::Arc,
11};
12use teloxide_core::types::{BusinessConnectionId, ChatId};
13use thiserror::Error;
14
15/// An error returned from [`RedisStorage`].
16#[derive(Debug, Error)]
17pub enum RedisStorageError<SE>
18where
19    SE: Debug + Display,
20{
21    #[error("parsing/serializing error: {0}")]
22    SerdeError(SE),
23
24    #[error("error from Redis: {0}")]
25    RedisError(#[from] redis::RedisError),
26
27    #[error("error creating redis pool: {0}")]
28    CreatePoolError(#[from] CreatePoolError),
29
30    #[error("redis pool error: {0}")]
31    PoolError(#[from] PoolError),
32
33    /// Returned from [`RedisStorage::remove_dialogue`].
34    #[error("row not found")]
35    DialogueNotFound,
36}
37
38/// A dialogue storage based on [Redis](https://redis.io/).
39///
40/// Ordinary dialogue keys are unprefixed decimal chat IDs; business keys
41/// start with `teloxide:dialogue:business:`. Use a dedicated Redis database
42/// if other applications store keys in these namespaces.
43pub struct RedisStorage<S> {
44    pool: deadpool_redis::Pool,
45    serializer: S,
46}
47
48impl<S> RedisStorage<S> {
49    pub async fn open(
50        url: &str,
51        serializer: S,
52    ) -> Result<Arc<Self>, RedisStorageError<Infallible>> {
53        let config = deadpool_redis::Config::from_url(url);
54        let pool = config.create_pool(Some(Runtime::Tokio1))?;
55
56        Ok(Arc::new(Self { pool, serializer }))
57    }
58}
59
60impl<S, D> Storage<D> for RedisStorage<S>
61where
62    S: Send + Sync + Serializer<D> + 'static,
63    D: Send + Serialize + DeserializeOwned + 'static,
64    <S as Serializer<D>>::Error: Debug + Display,
65{
66    type Error = RedisStorageError<<S as Serializer<D>>::Error>;
67
68    fn remove_dialogue(
69        self: Arc<Self>,
70        key: DialogueKey,
71    ) -> BoxFuture<'static, Result<(), Self::Error>> {
72        Box::pin(async move {
73            let deleted: u64 = self.pool.get().await?.del(encode_key(key)).await?;
74            if deleted == 0 {
75                return Err(RedisStorageError::DialogueNotFound);
76            }
77            Ok(())
78        })
79    }
80
81    fn update_dialogue(
82        self: Arc<Self>,
83        key: DialogueKey,
84        dialogue: D,
85    ) -> BoxFuture<'static, Result<(), Self::Error>> {
86        Box::pin(async move {
87            let dialogue =
88                self.serializer.serialize(&dialogue).map_err(RedisStorageError::SerdeError)?;
89            () = self.pool.get().await?.set(encode_key(key), dialogue).await?;
90            Ok(())
91        })
92    }
93
94    fn get_dialogue(
95        self: Arc<Self>,
96        key: DialogueKey,
97    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
98        Box::pin(async move {
99            self.pool
100                .get()
101                .await?
102                .get::<_, Option<Vec<u8>>>(encode_key(key))
103                .await?
104                .map(|d| self.serializer.deserialize(&d).map_err(RedisStorageError::SerdeError))
105                .transpose()
106        })
107    }
108
109    fn get_or_insert_dialogue(
110        self: Arc<Self>,
111        key: DialogueKey,
112        default: fn() -> D,
113        reset_incompatible: bool,
114    ) -> BoxFuture<'static, Result<D, Self::Error>> {
115        Box::pin(async move {
116            let key = encode_key(key);
117            let key = key.as_str();
118            let pool = &self.pool;
119            initialize(
120                &self.serializer,
121                RedisStorageError::SerdeError,
122                default,
123                reset_incompatible,
124                || async { Ok(pool.get().await?.get(key).await?) },
125                |expected, bytes| async move {
126                    let mut conn = pool.get().await?;
127                    if let Some(expected) = expected {
128                        // Compare binary-safe serialized bytes and replace only the bad value read
129                        // above.
130                        Ok(redis::cmd("EVAL")
131                            .arg(
132                                "if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('SET', \
133                                 KEYS[1], ARGV[2]); return 1 else return 0 end",
134                            )
135                            .arg(1)
136                            .arg(key)
137                            .arg(expected)
138                            .arg(bytes)
139                            .query_async(&mut conn)
140                            .await?)
141                    } else {
142                        Ok(conn.set_nx(key, bytes).await?)
143                    }
144                },
145            )
146            .await
147        })
148    }
149}
150
151impl<S: Send + Sync + 'static> StorageKeys for RedisStorage<S> {
152    type Error = RedisStorageError<Infallible>;
153
154    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
155        Box::pin(async move {
156            let mut conn = self.pool.get().await?;
157            let mut cursor = 0u64;
158            let mut ids = HashSet::new();
159            loop {
160                // Use SCAN instead of blocking Redis with KEYS, and propagate errors
161                // from every page before returning the result.
162                let (next, keys): (u64, Vec<Vec<u8>>) =
163                    redis::cmd("SCAN").arg(cursor).query_async(&mut conn).await?;
164                ids.extend(keys.iter().filter_map(|key| decode_key(key)));
165                if next == 0 {
166                    return Ok(ids);
167                }
168                cursor = next;
169            }
170        })
171    }
172}
173
174const BUSINESS_PREFIX: &str = "teloxide:dialogue:business:";
175
176fn encode_key(key: DialogueKey) -> String {
177    let chat_id = key.chat_id.0;
178    match key.business_connection_id {
179        None => chat_id.to_string(),
180        Some(connection) => format!("{BUSINESS_PREFIX}{chat_id}:{}", connection.0),
181    }
182}
183
184fn decode_key(key: &[u8]) -> Option<DialogueKey> {
185    let key = std::str::from_utf8(key).ok()?;
186    let (id, connection) = match key.strip_prefix(BUSINESS_PREFIX) {
187        None => (key, None),
188        Some(rest) => {
189            let (id, connection) = rest.split_once(':')?;
190            (id, Some(BusinessConnectionId(connection.into())))
191        }
192    };
193    let chat_id: i64 = id.parse().ok()?;
194    (chat_id.to_string() == id)
195        .then_some(DialogueKey { chat_id: ChatId(chat_id), business_connection_id: connection })
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn redis_key_round_trips_without_aliases() {
204        let chat = ChatId(-123);
205        let plain = encode_key(chat.into());
206        assert_eq!(plain, "-123");
207        for id in ["", "a:b", "日本語"] {
208            let key = DialogueKey::business(chat, BusinessConnectionId(id.into()));
209            let encoded = encode_key(key.clone());
210            assert_ne!(encoded, plain);
211            assert_eq!(decode_key(encoded.as_bytes()), Some(key));
212        }
213        assert_eq!(decode_key(plain.as_bytes()), Some(chat.into()));
214        assert_eq!(decode_key(b"0123"), None);
215    }
216}