use super::{from_sql_key, initialize, sql_key, DialogueKey, Serializer, Storage, StorageKeys};
use futures::future::BoxFuture;
use serde::{de::DeserializeOwned, Serialize};
use sqlx::sqlite::SqlitePool;
use std::{
collections::HashSet,
convert::Infallible,
fmt::{Debug, Display},
sync::Arc,
};
use thiserror::Error;
pub struct SqliteStorage<S> {
pool: SqlitePool,
serializer: S,
}
#[derive(Debug, Error)]
pub enum SqliteStorageError<SE: Debug + Display> {
#[error("dialogue serialization error: {0}")]
SerdeError(SE),
#[error("sqlite error: {0}")]
SqliteError(#[from] sqlx::Error),
#[error("row not found")]
DialogueNotFound,
}
const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS teloxide_dialogues (
chat_id BIGINT NOT NULL,
business_scope TEXT NOT NULL DEFAULT '',
dialogue BLOB NOT NULL,
PRIMARY KEY (chat_id, business_scope)
)";
impl<S> SqliteStorage<S> {
pub async fn open(
path: &str,
serializer: S,
) -> Result<Arc<Self>, SqliteStorageError<Infallible>> {
let pool = SqlitePool::connect(format!("sqlite:{path}?mode=rwc").as_str()).await?;
let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
let scoped: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('teloxide_dialogues') WHERE name = \
'business_scope')",
)
.fetch_one(&mut *tx)
.await?;
let legacy: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pragma_table_info('teloxide_dialogues') WHERE name = \
'chat_id')",
)
.fetch_one(&mut *tx)
.await?;
if legacy && !scoped {
sqlx::query("ALTER TABLE teloxide_dialogues RENAME TO teloxide_dialogues_legacy")
.execute(&mut *tx)
.await?;
}
sqlx::query(CREATE_TABLE).execute(&mut *tx).await?;
if legacy && !scoped {
sqlx::query(
"INSERT INTO teloxide_dialogues (chat_id, dialogue) SELECT chat_id, dialogue FROM \
teloxide_dialogues_legacy",
)
.execute(&mut *tx)
.await?;
sqlx::query("DROP TABLE teloxide_dialogues_legacy").execute(&mut *tx).await?;
}
tx.commit().await?;
Ok(Arc::new(Self { pool, serializer }))
}
}
impl<S, D> Storage<D> for SqliteStorage<S>
where
S: Send + Sync + Serializer<D> + 'static,
D: Send + Serialize + DeserializeOwned + 'static,
S::Error: Debug + Display,
{
type Error = SqliteStorageError<S::Error>;
fn remove_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<(), Self::Error>> {
Box::pin(async move {
let (chat_id, scope) = sql_key(key);
let result = sqlx::query(
"DELETE FROM teloxide_dialogues WHERE chat_id = ? AND business_scope = ?",
)
.bind(chat_id)
.bind(scope)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(SqliteStorageError::DialogueNotFound);
}
Ok(())
})
}
fn update_dialogue(
self: Arc<Self>,
key: DialogueKey,
dialogue: D,
) -> BoxFuture<'static, Result<(), Self::Error>> {
Box::pin(async move {
let (chat_id, scope) = sql_key(key);
let bytes =
self.serializer.serialize(&dialogue).map_err(SqliteStorageError::SerdeError)?;
sqlx::query(
"INSERT INTO teloxide_dialogues (chat_id, business_scope, dialogue) VALUES (?, ?, \
?)
ON CONFLICT (chat_id, business_scope) DO UPDATE SET dialogue = \
excluded.dialogue",
)
.bind(chat_id)
.bind(scope)
.bind(bytes)
.execute(&self.pool)
.await?;
Ok(())
})
}
fn get_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
Box::pin(async move {
let (chat_id, scope) = sql_key(key);
read(&self.pool, chat_id, &scope)
.await?
.map(|bytes| {
self.serializer.deserialize(&bytes).map_err(SqliteStorageError::SerdeError)
})
.transpose()
})
}
fn get_or_insert_dialogue(
self: Arc<Self>,
key: DialogueKey,
default: fn() -> D,
reset_incompatible: bool,
) -> BoxFuture<'static, Result<D, Self::Error>> {
Box::pin(async move {
let (chat_id, scope) = sql_key(key);
let scope = scope.as_str();
let pool = &self.pool;
initialize(
&self.serializer,
SqliteStorageError::SerdeError,
default,
reset_incompatible,
|| async { Ok(read(pool, chat_id, scope).await?) },
|expected, bytes| async move {
Ok(compare_exchange(pool, chat_id, scope, expected, bytes).await?)
},
)
.await
})
}
}
impl<S: Send + Sync + 'static> StorageKeys for SqliteStorage<S> {
type Error = sqlx::Error;
fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
Box::pin(async move {
let keys = sqlx::query_as("SELECT chat_id, business_scope FROM teloxide_dialogues")
.fetch_all(&self.pool)
.await?;
Ok(keys.into_iter().map(from_sql_key).collect())
})
}
}
async fn read(
pool: &SqlitePool,
chat_id: i64,
scope: &str,
) -> Result<Option<Vec<u8>>, sqlx::Error> {
sqlx::query_scalar(
"SELECT dialogue FROM teloxide_dialogues WHERE chat_id = ? AND business_scope = ?",
)
.bind(chat_id)
.bind(scope)
.fetch_optional(pool)
.await
}
async fn compare_exchange(
pool: &SqlitePool,
chat_id: i64,
scope: &str,
expected: Option<Vec<u8>>,
bytes: Vec<u8>,
) -> Result<bool, sqlx::Error> {
let result = if let Some(expected) = expected {
sqlx::query(
"UPDATE teloxide_dialogues SET dialogue = ? WHERE chat_id = ? AND business_scope = ? \
AND dialogue = ?",
)
.bind(bytes)
.bind(chat_id)
.bind(scope)
.bind(expected)
.execute(pool)
.await?
} else {
sqlx::query(
"INSERT INTO teloxide_dialogues (chat_id, business_scope, dialogue) VALUES (?, ?, ?) \
ON CONFLICT (chat_id, business_scope) DO NOTHING",
)
.bind(chat_id)
.bind(scope)
.bind(bytes)
.execute(pool)
.await?
};
Ok(result.rows_affected() == 1)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{dispatching::dialogue::serializer::Json, types::ChatId};
#[tokio::test]
async fn initialization_recovers_only_from_deserialization_errors() {
let store = SqliteStorage::open(":memory:", Json).await.unwrap();
let key = DialogueKey::from(ChatId(1));
store.clone().update_dialogue(key.clone(), String::from("incompatible")).await.unwrap();
let default = || 17u32;
assert!(matches!(
store.clone().get_or_insert_dialogue(key.clone(), default, false).await,
Err(SqliteStorageError::SerdeError(_))
));
assert_eq!(
store.clone().get_or_insert_dialogue(key.clone(), default, true).await.unwrap(),
17
);
assert_eq!(
Storage::<u32>::get_dialogue(store.clone(), key.clone()).await.unwrap(),
Some(17)
);
store.pool.close().await;
assert!(matches!(
store.get_or_insert_dialogue(key, || -> u32 { panic!("not a bad state") }, true).await,
Err(SqliteStorageError::SqliteError(sqlx::Error::PoolClosed))
));
}
#[tokio::test]
async fn stale_initialization_cannot_overwrite_a_concurrent_write() {
let store = SqliteStorage::open(":memory:", Json).await.unwrap();
let key = DialogueKey::from(ChatId(1));
store.clone().update_dialogue(key, 42u32).await.unwrap();
assert!(!compare_exchange(&store.pool, 1, "", None, b"0".to_vec()).await.unwrap());
assert!(!compare_exchange(&store.pool, 1, "", Some(b"invalid".to_vec()), b"0".to_vec())
.await
.unwrap());
assert_eq!(read(&store.pool, 1, "").await.unwrap().unwrap(), b"42");
}
}