teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
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};

/// A storage with an erased error type.
pub type ErasedStorage<D> =
    dyn Storage<D, Error = Box<dyn std::error::Error + Send + Sync>> + Send + Sync;

/// Optional key enumeration, independent of the dialogue state and serializer.
pub trait StorageKeys {
    type Error;

    /// Returns the keys of all stored dialogues.
    #[must_use = "Futures are lazy and do nothing unless polled with .await"]
    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>>;
}

/// A storage of dialogues.
///
/// You can implement this trait for a structure that communicates with a DB and
/// be sure that after you restart your bot, all the dialogues won't be lost.
///
/// `Storage` is used only to store dialogue states, i.e. it can't be used as a
/// generic database.
///
/// Currently we support the following storages out of the box:
///
/// - [`InMemStorage`] -- a storage based on [`std::collections::HashMap`].
/// - [`RedisStorage`] -- a Redis-based storage.
/// - [`SqliteStorage`] -- an SQLite-based persistent storage.
///
/// [`InMemStorage`]: crate::dispatching::dialogue::InMemStorage
/// [`RedisStorage`]: crate::dispatching::dialogue::RedisStorage
/// [`SqliteStorage`]: crate::dispatching::dialogue::SqliteStorage
pub trait Storage<D> {
    type Error;

    /// Removes a dialogue indexed by `key`.
    ///
    /// If the dialogue indexed by `key` does not exist, this function
    /// results in an 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;

    /// Updates a dialogue indexed by `key` with `dialogue`.
    #[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;

    /// Returns the dialogue indexed by `key`.
    #[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>>;

    /// Returns the stored dialogue or initializes it with `default` if absent.
    /// Implementations must not overwrite a concurrently inserted dialogue.
    /// When `reset_incompatible` is true, implementations may also replace a
    /// state that fails to deserialize, but must not ignore other errors or
    /// overwrite a concurrent update.
    #[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>>;

    /// Erases [`Self::Error`] to [`std::error::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 the very value whose serialized representation was just stored.
            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) {
    // Use a non-null scope so that both databases enforce uniqueness for ordinary
    // chats.
    (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]));
    }
}