teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use super::{initialize, DialogueKey, Serializer, Storage, StorageKeys};
use deadpool_redis::{redis, CreatePoolError, PoolError, Runtime};
use futures::future::BoxFuture;
use redis::AsyncCommands;
use serde::{de::DeserializeOwned, Serialize};
use std::{
    collections::HashSet,
    convert::Infallible,
    fmt::{Debug, Display},
    sync::Arc,
};
use teloxide_core::types::{BusinessConnectionId, ChatId};
use thiserror::Error;

/// An error returned from [`RedisStorage`].
#[derive(Debug, Error)]
pub enum RedisStorageError<SE>
where
    SE: Debug + Display,
{
    #[error("parsing/serializing error: {0}")]
    SerdeError(SE),

    #[error("error from Redis: {0}")]
    RedisError(#[from] redis::RedisError),

    #[error("error creating redis pool: {0}")]
    CreatePoolError(#[from] CreatePoolError),

    #[error("redis pool error: {0}")]
    PoolError(#[from] PoolError),

    /// Returned from [`RedisStorage::remove_dialogue`].
    #[error("row not found")]
    DialogueNotFound,
}

/// A dialogue storage based on [Redis](https://redis.io/).
///
/// Ordinary dialogue keys are unprefixed decimal chat IDs; business keys
/// start with `teloxide:dialogue:business:`. Use a dedicated Redis database
/// if other applications store keys in these namespaces.
pub struct RedisStorage<S> {
    pool: deadpool_redis::Pool,
    serializer: S,
}

impl<S> RedisStorage<S> {
    pub async fn open(
        url: &str,
        serializer: S,
    ) -> Result<Arc<Self>, RedisStorageError<Infallible>> {
        let config = deadpool_redis::Config::from_url(url);
        let pool = config.create_pool(Some(Runtime::Tokio1))?;

        Ok(Arc::new(Self { pool, serializer }))
    }
}

impl<S, D> Storage<D> for RedisStorage<S>
where
    S: Send + Sync + Serializer<D> + 'static,
    D: Send + Serialize + DeserializeOwned + 'static,
    <S as Serializer<D>>::Error: Debug + Display,
{
    type Error = RedisStorageError<<S as Serializer<D>>::Error>;

    fn remove_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
    ) -> BoxFuture<'static, Result<(), Self::Error>> {
        Box::pin(async move {
            let deleted: u64 = self.pool.get().await?.del(encode_key(key)).await?;
            if deleted == 0 {
                return Err(RedisStorageError::DialogueNotFound);
            }
            Ok(())
        })
    }

    fn update_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
        dialogue: D,
    ) -> BoxFuture<'static, Result<(), Self::Error>> {
        Box::pin(async move {
            let dialogue =
                self.serializer.serialize(&dialogue).map_err(RedisStorageError::SerdeError)?;
            () = self.pool.get().await?.set(encode_key(key), dialogue).await?;
            Ok(())
        })
    }

    fn get_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
        Box::pin(async move {
            self.pool
                .get()
                .await?
                .get::<_, Option<Vec<u8>>>(encode_key(key))
                .await?
                .map(|d| self.serializer.deserialize(&d).map_err(RedisStorageError::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 key = encode_key(key);
            let key = key.as_str();
            let pool = &self.pool;
            initialize(
                &self.serializer,
                RedisStorageError::SerdeError,
                default,
                reset_incompatible,
                || async { Ok(pool.get().await?.get(key).await?) },
                |expected, bytes| async move {
                    let mut conn = pool.get().await?;
                    if let Some(expected) = expected {
                        // Compare binary-safe serialized bytes and replace only the bad value read
                        // above.
                        Ok(redis::cmd("EVAL")
                            .arg(
                                "if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('SET', \
                                 KEYS[1], ARGV[2]); return 1 else return 0 end",
                            )
                            .arg(1)
                            .arg(key)
                            .arg(expected)
                            .arg(bytes)
                            .query_async(&mut conn)
                            .await?)
                    } else {
                        Ok(conn.set_nx(key, bytes).await?)
                    }
                },
            )
            .await
        })
    }
}

impl<S: Send + Sync + 'static> StorageKeys for RedisStorage<S> {
    type Error = RedisStorageError<Infallible>;

    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
        Box::pin(async move {
            let mut conn = self.pool.get().await?;
            let mut cursor = 0u64;
            let mut ids = HashSet::new();
            loop {
                // Use SCAN instead of blocking Redis with KEYS, and propagate errors
                // from every page before returning the result.
                let (next, keys): (u64, Vec<Vec<u8>>) =
                    redis::cmd("SCAN").arg(cursor).query_async(&mut conn).await?;
                ids.extend(keys.iter().filter_map(|key| decode_key(key)));
                if next == 0 {
                    return Ok(ids);
                }
                cursor = next;
            }
        })
    }
}

const BUSINESS_PREFIX: &str = "teloxide:dialogue:business:";

fn encode_key(key: DialogueKey) -> String {
    let chat_id = key.chat_id.0;
    match key.business_connection_id {
        None => chat_id.to_string(),
        Some(connection) => format!("{BUSINESS_PREFIX}{chat_id}:{}", connection.0),
    }
}

fn decode_key(key: &[u8]) -> Option<DialogueKey> {
    let key = std::str::from_utf8(key).ok()?;
    let (id, connection) = match key.strip_prefix(BUSINESS_PREFIX) {
        None => (key, None),
        Some(rest) => {
            let (id, connection) = rest.split_once(':')?;
            (id, Some(BusinessConnectionId(connection.into())))
        }
    };
    let chat_id: i64 = id.parse().ok()?;
    (chat_id.to_string() == id)
        .then_some(DialogueKey { chat_id: ChatId(chat_id), business_connection_id: connection })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redis_key_round_trips_without_aliases() {
        let chat = ChatId(-123);
        let plain = encode_key(chat.into());
        assert_eq!(plain, "-123");
        for id in ["", "a:b", "日本語"] {
            let key = DialogueKey::business(chat, BusinessConnectionId(id.into()));
            let encoded = encode_key(key.clone());
            assert_ne!(encoded, plain);
            assert_eq!(decode_key(encoded.as_bytes()), Some(key));
        }
        assert_eq!(decode_key(plain.as_bytes()), Some(chat.into()));
        assert_eq!(decode_key(b"0123"), None);
    }
}