teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use std::{
    collections::HashSet,
    convert::Infallible,
    fmt::{Debug, Display},
    str,
    sync::Arc,
};

use futures::future::BoxFuture;
use serde::{de::DeserializeOwned, Serialize};
use sqlx::postgres::{PgPool, PgPoolOptions};
use thiserror::Error;

use super::{from_sql_key, initialize, sql_key, DialogueKey, Serializer, Storage, StorageKeys};

/// An error returned from [`PostgresStorage`].
#[derive(Debug, Error)]
pub enum PostgresStorageError<SE>
where
    SE: Debug + Display,
{
    #[error("dialogue serialization error: {0}")]
    SerdeError(SE),

    #[error("postgres error: {0}")]
    PostgresError(#[from] sqlx::Error),

    // TODO maybe add chat_id for the sake of completeness?
    #[error("row not found")]
    DialogueNotFound,
}

/// A persistent dialogue storage based on [PostgreSQL](https://www.postgresql.org/)
pub struct PostgresStorage<S> {
    pool: PgPool,
    serializer: S,
}

impl<S> PostgresStorage<S> {
    /// Opens a connection pool to the [Postgres](https://www.postgresql.org/) database and creates the table
    /// for storing dialogues.
    ///
    /// Parameters:
    /// - database_url: full url to the postgres database, for example
    ///   `"postgres://postgres:password@localhost/test")`
    /// - max_connections: number of connections in creating connection pool. Be
    ///   mindful of the connection limits for your database, each connection
    ///   established with the Postgres creates a new process on the server side
    /// - serializer: what [`Serializer`] will be used to encode the dialogue
    ///   data. Available ones are: [`Json`], [`Bincode`], [`Cbor`]
    ///
    /// [`Json`]: crate::dispatching::dialogue::serializer::Json
    /// [`Bincode`]: crate::dispatching::dialogue::serializer::Bincode
    /// [`Cbor`]: crate::dispatching::dialogue::serializer::Cbor
    pub async fn open(
        database_url: &str,
        max_connections: u32,
        serializer: S,
    ) -> Result<Arc<Self>, PostgresStorageError<Infallible>> {
        let pool =
            PgPoolOptions::new().max_connections(max_connections).connect(database_url).await?;
        let mut tx = pool.begin().await?;
        // Serialize schema creation/migration across concurrent opens.
        sqlx::query("SELECT pg_advisory_xact_lock(1598376190, 1)").execute(&mut *tx).await?;
        sqlx::query(include_str!("postgres_storage/queries/create_teloxide_dialogues.sql"))
            .execute(&mut *tx)
            .await?;
        let scoped: bool = sqlx::query_scalar(
            "SELECT EXISTS(SELECT 1 FROM pg_attribute WHERE attrelid = \
             'teloxide_dialogues'::regclass AND attname = 'business_scope' AND NOT attisdropped)",
        )
        .fetch_one(&mut *tx)
        .await?;
        if !scoped {
            sqlx::query(
                "ALTER TABLE teloxide_dialogues ADD COLUMN business_scope TEXT NOT NULL DEFAULT \
                 '', DROP CONSTRAINT teloxide_dialogues_pkey, ADD PRIMARY KEY (chat_id, \
                 business_scope)",
            )
            .execute(&mut *tx)
            .await?;
        }
        tx.commit().await?;

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

// FIXME: these methods' bodies are almostly the same as SqliteStorage ones
// (except actual queries) Maybe combine them somehow?

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

    fn remove_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
    ) -> BoxFuture<'static, Result<(), Self::Error>>
    where
        D: Send + 'static,
    {
        Box::pin(async move {
            let (chat_id, scope) = sql_key(key);
            let deleted_rows_count =
                sqlx::query(include_str!("postgres_storage/queries/remove_dialogue.sql"))
                    .bind(chat_id)
                    .bind(scope)
                    .execute(&self.pool)
                    .await?
                    .rows_affected();

            if deleted_rows_count == 0 {
                return Err(PostgresStorageError::DialogueNotFound);
            }

            Ok(())
        })
    }

    fn update_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
        dialogue: D,
    ) -> BoxFuture<'static, Result<(), Self::Error>>
    where
        D: Send + 'static,
    {
        Box::pin(async move {
            let (chat_id, scope) = sql_key(key);
            let d =
                self.serializer.serialize(&dialogue).map_err(PostgresStorageError::SerdeError)?;
            sqlx::query(include_str!("postgres_storage/queries/update_dialogue.sql"))
                .bind(chat_id)
                .bind(scope)
                .bind(d)
                .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(|d| self.serializer.deserialize(&d).map_err(PostgresStorageError::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,
                PostgresStorageError::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 PostgresStorage<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(include_str!("postgres_storage/queries/keys.sql"))
                .fetch_all(&self.pool)
                .await?;
            Ok(keys.into_iter().map(from_sql_key).collect())
        })
    }
}

async fn read(pool: &PgPool, chat_id: i64, scope: &str) -> Result<Option<Vec<u8>>, sqlx::Error> {
    sqlx::query_scalar(include_str!("postgres_storage/queries/get_dialogue.sql"))
        .bind(chat_id)
        .bind(scope)
        .fetch_optional(pool)
        .await
}

async fn compare_exchange(
    pool: &PgPool,
    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 = $1 WHERE chat_id = $2 AND business_scope = \
             $3 AND dialogue = $4",
        )
        .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 ($1, $2, \
             $3) ON CONFLICT (chat_id, business_scope) DO NOTHING",
        )
        .bind(chat_id)
        .bind(scope)
        .bind(bytes)
        .execute(pool)
        .await?
    };
    Ok(result.rows_affected() == 1)
}