pub mod serializer;
mod in_mem_storage;
mod trace_storage;
#[cfg(feature = "redis-storage")]
mod redis_storage;
#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
mod sqlite_storage;
#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
mod postgres_storage;
use super::DialogueKey;
use futures::future::BoxFuture;
pub use self::{
in_mem_storage::{InMemStorage, InMemStorageError},
trace_storage::TraceStorage,
};
#[cfg(feature = "redis-storage")]
pub use redis_storage::{RedisStorage, RedisStorageError};
pub use serializer::Serializer;
use std::{collections::HashSet, sync::Arc};
#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
pub use sqlite_storage::{SqliteStorage, SqliteStorageError};
#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
pub use postgres_storage::{PostgresStorage, PostgresStorageError};
pub type ErasedStorage<D> =
dyn Storage<D, Error = Box<dyn std::error::Error + Send + Sync>> + Send + Sync;
pub trait StorageKeys {
type Error;
#[must_use = "Futures are lazy and do nothing unless polled with .await"]
fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>>;
}
pub trait Storage<D> {
type Error;
#[must_use = "Futures are lazy and do nothing unless polled with .await"]
fn remove_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static;
#[must_use = "Futures are lazy and do nothing unless polled with .await"]
fn update_dialogue(
self: Arc<Self>,
key: DialogueKey,
dialogue: D,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static;
#[must_use = "Futures are lazy and do nothing unless polled with .await"]
fn get_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<Option<D>, Self::Error>>;
#[must_use = "Futures are lazy and do nothing unless polled with .await"]
fn get_or_insert_dialogue(
self: Arc<Self>,
key: DialogueKey,
default: fn() -> D,
reset_incompatible: bool,
) -> BoxFuture<'static, Result<D, Self::Error>>;
#[must_use]
fn erase(self: Arc<Self>) -> Arc<ErasedStorage<D>>
where
D: 'static,
Self: Sized + Send + Sync + 'static,
Self::Error: std::error::Error + Send + Sync + 'static,
{
Arc::new(Eraser(self))
}
}
#[cfg(any(
feature = "redis-storage",
feature = "sqlite-storage-nativetls",
feature = "sqlite-storage-rustls",
feature = "postgres-storage-nativetls",
feature = "postgres-storage-rustls",
))]
async fn initialize<D, S, E, Read, Write>(
serializer: &S,
serde_error: impl Fn(S::Error) -> E,
default: fn() -> D,
reset_incompatible: bool,
mut read: impl FnMut() -> Read,
mut compare_exchange: impl FnMut(Option<Vec<u8>>, Vec<u8>) -> Write,
) -> Result<D, E>
where
S: Serializer<D>,
Read: std::future::Future<Output = Result<Option<Vec<u8>>, E>>,
Write: std::future::Future<Output = Result<bool, E>>,
{
let mut candidate = None;
loop {
let stored = read().await?;
if let Some(bytes) = &stored {
match serializer.deserialize(bytes) {
Ok(state) => return Ok(state),
Err(error) if !reset_incompatible => return Err(serde_error(error)),
Err(_) => {}
}
}
if candidate.is_none() {
let state = default();
let bytes = serializer.serialize(&state).map_err(&serde_error)?;
candidate = Some((state, bytes));
}
let (_, bytes) = candidate.as_ref().unwrap();
if compare_exchange(stored, bytes.clone()).await? {
return Ok(candidate.unwrap().0);
}
}
}
#[cfg(any(
feature = "sqlite-storage-nativetls",
feature = "sqlite-storage-rustls",
feature = "postgres-storage-nativetls",
feature = "postgres-storage-rustls",
))]
fn sql_key(key: DialogueKey) -> (i64, String) {
(key.chat_id.0, key.business_connection_id.map_or_else(String::new, |id| format!("b{}", id.0)))
}
#[cfg(any(
feature = "sqlite-storage-nativetls",
feature = "sqlite-storage-rustls",
feature = "postgres-storage-nativetls",
feature = "postgres-storage-rustls",
))]
fn from_sql_key((chat_id, scope): (i64, String)) -> DialogueKey {
use teloxide_core::types::{BusinessConnectionId, ChatId};
DialogueKey {
chat_id: ChatId(chat_id),
business_connection_id: scope.strip_prefix('b').map(|id| BusinessConnectionId(id.into())),
}
}
struct Eraser<S>(Arc<S>);
impl<D: 'static, S> Storage<D> for Eraser<S>
where
S: Storage<D> + Send + Sync + 'static,
S::Error: std::error::Error + Send + Sync + 'static,
{
type Error = Box<dyn std::error::Error + Send + Sync>;
fn remove_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static,
{
Box::pin(async move { self.0.clone().remove_dialogue(key).await.map_err(Into::into) })
}
fn update_dialogue(
self: Arc<Self>,
key: DialogueKey,
dialogue: D,
) -> BoxFuture<'static, Result<(), Self::Error>>
where
D: Send + 'static,
{
Box::pin(
async move { self.0.clone().update_dialogue(key, dialogue).await.map_err(Into::into) },
)
}
fn get_dialogue(
self: Arc<Self>,
key: DialogueKey,
) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
Box::pin(async move { self.0.clone().get_dialogue(key).await.map_err(Into::into) })
}
fn get_or_insert_dialogue(
self: Arc<Self>,
key: DialogueKey,
default: fn() -> D,
reset_incompatible: bool,
) -> BoxFuture<'static, Result<D, Self::Error>> {
let initialize = self.0.clone().get_or_insert_dialogue(key, default, reset_incompatible);
Box::pin(async move { initialize.await.map_err(Into::into) })
}
}
#[cfg(test)]
mod tests {
use super::*;
use teloxide_core::types::{BusinessConnectionId, ChatId};
#[tokio::test]
async fn test_erased() {
let chat = ChatId(123);
let plain = chat.into();
let business = DialogueKey::business(chat, BusinessConnectionId("business".into()));
let other = DialogueKey::business(chat, BusinessConnectionId("other".into()));
let store = TraceStorage::new(InMemStorage::new());
let erased = store.clone().erase();
assert!(store.clone().keys().await.unwrap().is_empty());
erased.clone().update_dialogue(plain, 1).await.unwrap();
assert_eq!(
erased.clone().get_or_insert_dialogue(business.clone(), || 2, false).await.unwrap(),
2
);
assert_eq!(erased.clone().get_dialogue(chat.into()).await.unwrap(), Some(1));
assert_eq!(erased.clone().get_dialogue(business.clone()).await.unwrap(), Some(2));
assert_eq!(erased.clone().get_dialogue(other).await.unwrap(), None);
assert_eq!(
store.clone().keys().await.unwrap(),
HashSet::from([chat.into(), business.clone()])
);
erased.clone().remove_dialogue(chat.into()).await.unwrap();
assert_eq!(erased.clone().get_dialogue(chat.into()).await.unwrap(), None);
assert_eq!(store.keys().await.unwrap(), HashSet::from([business]));
}
}