teloxide-fork 0.20.0

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

use super::{DialogueKey, Storage, StorageKeys};
use futures::future::BoxFuture;

/// A dialogue storage wrapper which logs all actions performed on an underlying
/// storage.
///
/// Reports about any dialogue action via [`log::Level::Trace`].
pub struct TraceStorage<S> {
    inner: Arc<S>,
}

impl<S> TraceStorage<S> {
    #[must_use = "This function is pure, that is does nothing unless its output is used"]
    pub fn new(inner: Arc<S>) -> Arc<Self> {
        Arc::new(Self { inner })
    }

    #[must_use = "This function is pure, that is does nothing unless its output is used"]
    pub fn into_inner(self) -> Arc<S> {
        self.inner
    }
}

impl<S, D> Storage<D> for TraceStorage<S>
where
    D: Debug,
    S: Storage<D> + Send + Sync + 'static,
{
    type Error = <S as Storage<D>>::Error;

    fn remove_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
    ) -> BoxFuture<'static, Result<(), Self::Error>>
    where
        D: Send + 'static,
    {
        log::trace!("Removing dialogue {key:?}");
        self.inner.clone().remove_dialogue(key)
    }

    fn update_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
        dialogue: D,
    ) -> BoxFuture<'static, Result<(), Self::Error>>
    where
        D: Send + 'static,
    {
        Box::pin(async move {
            let to = format!("{dialogue:#?}");
            self.inner.clone().update_dialogue(key.clone(), dialogue).await?;
            log::trace!("Updated dialogue {key:?}: {to:#?}");
            Ok(())
        })
    }

    fn get_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
        log::trace!("Requested dialogue {key:?}");
        self.inner.clone().get_dialogue(key)
    }

    fn get_or_insert_dialogue(
        self: Arc<Self>,
        key: DialogueKey,
        default: fn() -> D,
        reset_incompatible: bool,
    ) -> BoxFuture<'static, Result<D, Self::Error>> {
        log::trace!("Requested or initialized dialogue {key:?}");
        self.inner.clone().get_or_insert_dialogue(key, default, reset_incompatible)
    }
}

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

    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
        log::trace!("Requested keys");
        self.inner.clone().keys()
    }
}