teloxide/dispatching/dialogue/storage/
sqlite_storage.rs1use super::{from_sql_key, initialize, sql_key, DialogueKey, Serializer, Storage, StorageKeys};
2use futures::future::BoxFuture;
3use serde::{de::DeserializeOwned, Serialize};
4use sqlx::sqlite::SqlitePool;
5use std::{
6 collections::HashSet,
7 convert::Infallible,
8 fmt::{Debug, Display},
9 sync::Arc,
10};
11use thiserror::Error;
12
13pub struct SqliteStorage<S> {
15 pool: SqlitePool,
16 serializer: S,
17}
18
19#[derive(Debug, Error)]
21pub enum SqliteStorageError<SE: Debug + Display> {
22 #[error("dialogue serialization error: {0}")]
23 SerdeError(SE),
24
25 #[error("sqlite error: {0}")]
26 SqliteError(#[from] sqlx::Error),
27
28 #[error("row not found")]
30 DialogueNotFound,
31}
32
33const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS teloxide_dialogues (
34 chat_id BIGINT NOT NULL,
35 business_scope TEXT NOT NULL DEFAULT '',
36 dialogue BLOB NOT NULL,
37 PRIMARY KEY (chat_id, business_scope)
38)";
39
40impl<S> SqliteStorage<S> {
41 pub async fn open(
42 path: &str,
43 serializer: S,
44 ) -> Result<Arc<Self>, SqliteStorageError<Infallible>> {
45 let pool = SqlitePool::connect(format!("sqlite:{path}?mode=rwc").as_str()).await?;
46 let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
48 let scoped: bool = sqlx::query_scalar(
49 "SELECT EXISTS(SELECT 1 FROM pragma_table_info('teloxide_dialogues') WHERE name = \
50 'business_scope')",
51 )
52 .fetch_one(&mut *tx)
53 .await?;
54 let legacy: bool = sqlx::query_scalar(
55 "SELECT EXISTS(SELECT 1 FROM pragma_table_info('teloxide_dialogues') WHERE name = \
56 'chat_id')",
57 )
58 .fetch_one(&mut *tx)
59 .await?;
60 if legacy && !scoped {
61 sqlx::query("ALTER TABLE teloxide_dialogues RENAME TO teloxide_dialogues_legacy")
62 .execute(&mut *tx)
63 .await?;
64 }
65 sqlx::query(CREATE_TABLE).execute(&mut *tx).await?;
66 if legacy && !scoped {
67 sqlx::query(
68 "INSERT INTO teloxide_dialogues (chat_id, dialogue) SELECT chat_id, dialogue FROM \
69 teloxide_dialogues_legacy",
70 )
71 .execute(&mut *tx)
72 .await?;
73 sqlx::query("DROP TABLE teloxide_dialogues_legacy").execute(&mut *tx).await?;
74 }
75 tx.commit().await?;
76
77 Ok(Arc::new(Self { pool, serializer }))
78 }
79}
80
81impl<S, D> Storage<D> for SqliteStorage<S>
82where
83 S: Send + Sync + Serializer<D> + 'static,
84 D: Send + Serialize + DeserializeOwned + 'static,
85 S::Error: Debug + Display,
86{
87 type Error = SqliteStorageError<S::Error>;
88
89 fn remove_dialogue(
90 self: Arc<Self>,
91 key: DialogueKey,
92 ) -> BoxFuture<'static, Result<(), Self::Error>> {
93 Box::pin(async move {
94 let (chat_id, scope) = sql_key(key);
95 let result = sqlx::query(
96 "DELETE FROM teloxide_dialogues WHERE chat_id = ? AND business_scope = ?",
97 )
98 .bind(chat_id)
99 .bind(scope)
100 .execute(&self.pool)
101 .await?;
102 if result.rows_affected() == 0 {
103 return Err(SqliteStorageError::DialogueNotFound);
104 }
105 Ok(())
106 })
107 }
108
109 fn update_dialogue(
110 self: Arc<Self>,
111 key: DialogueKey,
112 dialogue: D,
113 ) -> BoxFuture<'static, Result<(), Self::Error>> {
114 Box::pin(async move {
115 let (chat_id, scope) = sql_key(key);
116 let bytes =
117 self.serializer.serialize(&dialogue).map_err(SqliteStorageError::SerdeError)?;
118 sqlx::query(
119 "INSERT INTO teloxide_dialogues (chat_id, business_scope, dialogue) VALUES (?, ?, \
120 ?)
121 ON CONFLICT (chat_id, business_scope) DO UPDATE SET dialogue = \
122 excluded.dialogue",
123 )
124 .bind(chat_id)
125 .bind(scope)
126 .bind(bytes)
127 .execute(&self.pool)
128 .await?;
129 Ok(())
130 })
131 }
132
133 fn get_dialogue(
134 self: Arc<Self>,
135 key: DialogueKey,
136 ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
137 Box::pin(async move {
138 let (chat_id, scope) = sql_key(key);
139 read(&self.pool, chat_id, &scope)
140 .await?
141 .map(|bytes| {
142 self.serializer.deserialize(&bytes).map_err(SqliteStorageError::SerdeError)
143 })
144 .transpose()
145 })
146 }
147
148 fn get_or_insert_dialogue(
149 self: Arc<Self>,
150 key: DialogueKey,
151 default: fn() -> D,
152 reset_incompatible: bool,
153 ) -> BoxFuture<'static, Result<D, Self::Error>> {
154 Box::pin(async move {
155 let (chat_id, scope) = sql_key(key);
156 let scope = scope.as_str();
157 let pool = &self.pool;
158 initialize(
159 &self.serializer,
160 SqliteStorageError::SerdeError,
161 default,
162 reset_incompatible,
163 || async { Ok(read(pool, chat_id, scope).await?) },
164 |expected, bytes| async move {
165 Ok(compare_exchange(pool, chat_id, scope, expected, bytes).await?)
166 },
167 )
168 .await
169 })
170 }
171}
172
173impl<S: Send + Sync + 'static> StorageKeys for SqliteStorage<S> {
174 type Error = sqlx::Error;
175
176 fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
177 Box::pin(async move {
178 let keys = sqlx::query_as("SELECT chat_id, business_scope FROM teloxide_dialogues")
179 .fetch_all(&self.pool)
180 .await?;
181 Ok(keys.into_iter().map(from_sql_key).collect())
182 })
183 }
184}
185
186async fn read(
187 pool: &SqlitePool,
188 chat_id: i64,
189 scope: &str,
190) -> Result<Option<Vec<u8>>, sqlx::Error> {
191 sqlx::query_scalar(
192 "SELECT dialogue FROM teloxide_dialogues WHERE chat_id = ? AND business_scope = ?",
193 )
194 .bind(chat_id)
195 .bind(scope)
196 .fetch_optional(pool)
197 .await
198}
199
200async fn compare_exchange(
201 pool: &SqlitePool,
202 chat_id: i64,
203 scope: &str,
204 expected: Option<Vec<u8>>,
205 bytes: Vec<u8>,
206) -> Result<bool, sqlx::Error> {
207 let result = if let Some(expected) = expected {
208 sqlx::query(
209 "UPDATE teloxide_dialogues SET dialogue = ? WHERE chat_id = ? AND business_scope = ? \
210 AND dialogue = ?",
211 )
212 .bind(bytes)
213 .bind(chat_id)
214 .bind(scope)
215 .bind(expected)
216 .execute(pool)
217 .await?
218 } else {
219 sqlx::query(
220 "INSERT INTO teloxide_dialogues (chat_id, business_scope, dialogue) VALUES (?, ?, ?) \
221 ON CONFLICT (chat_id, business_scope) DO NOTHING",
222 )
223 .bind(chat_id)
224 .bind(scope)
225 .bind(bytes)
226 .execute(pool)
227 .await?
228 };
229 Ok(result.rows_affected() == 1)
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235 use crate::{dispatching::dialogue::serializer::Json, types::ChatId};
236
237 #[tokio::test]
238 async fn initialization_recovers_only_from_deserialization_errors() {
239 let store = SqliteStorage::open(":memory:", Json).await.unwrap();
240 let key = DialogueKey::from(ChatId(1));
241 store.clone().update_dialogue(key.clone(), String::from("incompatible")).await.unwrap();
242 let default = || 17u32;
243 assert!(matches!(
244 store.clone().get_or_insert_dialogue(key.clone(), default, false).await,
245 Err(SqliteStorageError::SerdeError(_))
246 ));
247 assert_eq!(
248 store.clone().get_or_insert_dialogue(key.clone(), default, true).await.unwrap(),
249 17
250 );
251 assert_eq!(
252 Storage::<u32>::get_dialogue(store.clone(), key.clone()).await.unwrap(),
253 Some(17)
254 );
255 store.pool.close().await;
256 assert!(matches!(
257 store.get_or_insert_dialogue(key, || -> u32 { panic!("not a bad state") }, true).await,
258 Err(SqliteStorageError::SqliteError(sqlx::Error::PoolClosed))
259 ));
260 }
261
262 #[tokio::test]
263 async fn stale_initialization_cannot_overwrite_a_concurrent_write() {
264 let store = SqliteStorage::open(":memory:", Json).await.unwrap();
265 let key = DialogueKey::from(ChatId(1));
266 store.clone().update_dialogue(key, 42u32).await.unwrap();
267 assert!(!compare_exchange(&store.pool, 1, "", None, b"0".to_vec()).await.unwrap());
268 assert!(!compare_exchange(&store.pool, 1, "", Some(b"invalid".to_vec()), b"0".to_vec())
269 .await
270 .unwrap());
271 assert_eq!(read(&store.pool, 1, "").await.unwrap().unwrap(), b"42");
272 }
273}