Skip to main content

teloxide/dispatching/dialogue/
storage.rs

1pub mod serializer;
2
3mod in_mem_storage;
4mod trace_storage;
5
6#[cfg(feature = "redis-storage")]
7mod redis_storage;
8
9#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
10mod sqlite_storage;
11
12#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
13mod postgres_storage;
14
15use super::DialogueKey;
16use futures::future::BoxFuture;
17
18pub use self::{
19    in_mem_storage::{InMemStorage, InMemStorageError},
20    trace_storage::TraceStorage,
21};
22
23#[cfg(feature = "redis-storage")]
24pub use redis_storage::{RedisStorage, RedisStorageError};
25pub use serializer::Serializer;
26use std::{collections::HashSet, sync::Arc};
27
28#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
29pub use sqlite_storage::{SqliteStorage, SqliteStorageError};
30
31#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
32pub use postgres_storage::{PostgresStorage, PostgresStorageError};
33
34/// A storage with an erased error type.
35pub type ErasedStorage<D> =
36    dyn Storage<D, Error = Box<dyn std::error::Error + Send + Sync>> + Send + Sync;
37
38/// Optional key enumeration, independent of the dialogue state and serializer.
39pub trait StorageKeys {
40    type Error;
41
42    /// Returns the keys of all stored dialogues.
43    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
44    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>>;
45}
46
47/// A storage of dialogues.
48///
49/// You can implement this trait for a structure that communicates with a DB and
50/// be sure that after you restart your bot, all the dialogues won't be lost.
51///
52/// `Storage` is used only to store dialogue states, i.e. it can't be used as a
53/// generic database.
54///
55/// Currently we support the following storages out of the box:
56///
57/// - [`InMemStorage`] -- a storage based on [`std::collections::HashMap`].
58/// - [`RedisStorage`] -- a Redis-based storage.
59/// - [`SqliteStorage`] -- an SQLite-based persistent storage.
60///
61/// [`InMemStorage`]: crate::dispatching::dialogue::InMemStorage
62/// [`RedisStorage`]: crate::dispatching::dialogue::RedisStorage
63/// [`SqliteStorage`]: crate::dispatching::dialogue::SqliteStorage
64pub trait Storage<D> {
65    type Error;
66
67    /// Removes a dialogue indexed by `key`.
68    ///
69    /// If the dialogue indexed by `key` does not exist, this function
70    /// results in an error.
71    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
72    fn remove_dialogue(
73        self: Arc<Self>,
74        key: DialogueKey,
75    ) -> BoxFuture<'static, Result<(), Self::Error>>
76    where
77        D: Send + 'static;
78
79    /// Updates a dialogue indexed by `key` with `dialogue`.
80    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
81    fn update_dialogue(
82        self: Arc<Self>,
83        key: DialogueKey,
84        dialogue: D,
85    ) -> BoxFuture<'static, Result<(), Self::Error>>
86    where
87        D: Send + 'static;
88
89    /// Returns the dialogue indexed by `key`.
90    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
91    fn get_dialogue(
92        self: Arc<Self>,
93        key: DialogueKey,
94    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>>;
95
96    /// Returns the stored dialogue or initializes it with `default` if absent.
97    /// Implementations must not overwrite a concurrently inserted dialogue.
98    /// When `reset_incompatible` is true, implementations may also replace a
99    /// state that fails to deserialize, but must not ignore other errors or
100    /// overwrite a concurrent update.
101    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
102    fn get_or_insert_dialogue(
103        self: Arc<Self>,
104        key: DialogueKey,
105        default: fn() -> D,
106        reset_incompatible: bool,
107    ) -> BoxFuture<'static, Result<D, Self::Error>>;
108
109    /// Erases [`Self::Error`] to [`std::error::Error`].
110    #[must_use]
111    fn erase(self: Arc<Self>) -> Arc<ErasedStorage<D>>
112    where
113        D: 'static,
114        Self: Sized + Send + Sync + 'static,
115        Self::Error: std::error::Error + Send + Sync + 'static,
116    {
117        Arc::new(Eraser(self))
118    }
119}
120
121#[cfg(any(
122    feature = "redis-storage",
123    feature = "sqlite-storage-nativetls",
124    feature = "sqlite-storage-rustls",
125    feature = "postgres-storage-nativetls",
126    feature = "postgres-storage-rustls",
127))]
128async fn initialize<D, S, E, Read, Write>(
129    serializer: &S,
130    serde_error: impl Fn(S::Error) -> E,
131    default: fn() -> D,
132    reset_incompatible: bool,
133    mut read: impl FnMut() -> Read,
134    mut compare_exchange: impl FnMut(Option<Vec<u8>>, Vec<u8>) -> Write,
135) -> Result<D, E>
136where
137    S: Serializer<D>,
138    Read: std::future::Future<Output = Result<Option<Vec<u8>>, E>>,
139    Write: std::future::Future<Output = Result<bool, E>>,
140{
141    let mut candidate = None;
142    loop {
143        let stored = read().await?;
144        if let Some(bytes) = &stored {
145            match serializer.deserialize(bytes) {
146                Ok(state) => return Ok(state),
147                Err(error) if !reset_incompatible => return Err(serde_error(error)),
148                Err(_) => {}
149            }
150        }
151
152        if candidate.is_none() {
153            let state = default();
154            let bytes = serializer.serialize(&state).map_err(&serde_error)?;
155            candidate = Some((state, bytes));
156        }
157
158        let (_, bytes) = candidate.as_ref().unwrap();
159        if compare_exchange(stored, bytes.clone()).await? {
160            // Return the very value whose serialized representation was just stored.
161            return Ok(candidate.unwrap().0);
162        }
163    }
164}
165
166#[cfg(any(
167    feature = "sqlite-storage-nativetls",
168    feature = "sqlite-storage-rustls",
169    feature = "postgres-storage-nativetls",
170    feature = "postgres-storage-rustls",
171))]
172fn sql_key(key: DialogueKey) -> (i64, String) {
173    // Use a non-null scope so that both databases enforce uniqueness for ordinary
174    // chats.
175    (key.chat_id.0, key.business_connection_id.map_or_else(String::new, |id| format!("b{}", id.0)))
176}
177
178#[cfg(any(
179    feature = "sqlite-storage-nativetls",
180    feature = "sqlite-storage-rustls",
181    feature = "postgres-storage-nativetls",
182    feature = "postgres-storage-rustls",
183))]
184fn from_sql_key((chat_id, scope): (i64, String)) -> DialogueKey {
185    use teloxide_core::types::{BusinessConnectionId, ChatId};
186
187    DialogueKey {
188        chat_id: ChatId(chat_id),
189        business_connection_id: scope.strip_prefix('b').map(|id| BusinessConnectionId(id.into())),
190    }
191}
192
193struct Eraser<S>(Arc<S>);
194
195impl<D: 'static, S> Storage<D> for Eraser<S>
196where
197    S: Storage<D> + Send + Sync + 'static,
198    S::Error: std::error::Error + Send + Sync + 'static,
199{
200    type Error = Box<dyn std::error::Error + Send + Sync>;
201
202    fn remove_dialogue(
203        self: Arc<Self>,
204        key: DialogueKey,
205    ) -> BoxFuture<'static, Result<(), Self::Error>>
206    where
207        D: Send + 'static,
208    {
209        Box::pin(async move { self.0.clone().remove_dialogue(key).await.map_err(Into::into) })
210    }
211
212    fn update_dialogue(
213        self: Arc<Self>,
214        key: DialogueKey,
215        dialogue: D,
216    ) -> BoxFuture<'static, Result<(), Self::Error>>
217    where
218        D: Send + 'static,
219    {
220        Box::pin(
221            async move { self.0.clone().update_dialogue(key, dialogue).await.map_err(Into::into) },
222        )
223    }
224
225    fn get_dialogue(
226        self: Arc<Self>,
227        key: DialogueKey,
228    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
229        Box::pin(async move { self.0.clone().get_dialogue(key).await.map_err(Into::into) })
230    }
231
232    fn get_or_insert_dialogue(
233        self: Arc<Self>,
234        key: DialogueKey,
235        default: fn() -> D,
236        reset_incompatible: bool,
237    ) -> BoxFuture<'static, Result<D, Self::Error>> {
238        let initialize = self.0.clone().get_or_insert_dialogue(key, default, reset_incompatible);
239        Box::pin(async move { initialize.await.map_err(Into::into) })
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use teloxide_core::types::{BusinessConnectionId, ChatId};
247
248    #[tokio::test]
249    async fn test_erased() {
250        let chat = ChatId(123);
251        let plain = chat.into();
252        let business = DialogueKey::business(chat, BusinessConnectionId("business".into()));
253        let other = DialogueKey::business(chat, BusinessConnectionId("other".into()));
254
255        let store = TraceStorage::new(InMemStorage::new());
256        let erased = store.clone().erase();
257        assert!(store.clone().keys().await.unwrap().is_empty());
258        erased.clone().update_dialogue(plain, 1).await.unwrap();
259        assert_eq!(
260            erased.clone().get_or_insert_dialogue(business.clone(), || 2, false).await.unwrap(),
261            2
262        );
263        assert_eq!(erased.clone().get_dialogue(chat.into()).await.unwrap(), Some(1));
264        assert_eq!(erased.clone().get_dialogue(business.clone()).await.unwrap(), Some(2));
265        assert_eq!(erased.clone().get_dialogue(other).await.unwrap(), None);
266        assert_eq!(
267            store.clone().keys().await.unwrap(),
268            HashSet::from([chat.into(), business.clone()])
269        );
270        erased.clone().remove_dialogue(chat.into()).await.unwrap();
271        assert_eq!(erased.clone().get_dialogue(chat.into()).await.unwrap(), None);
272        assert_eq!(store.keys().await.unwrap(), HashSet::from([business]));
273    }
274}