#[cfg(feature = "redis-storage")]
pub use self::{RedisStorage, RedisStorageError};
#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
pub use self::{SqliteStorage, SqliteStorageError};
#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
pub use self::{PostgresStorage, PostgresStorageError};
pub use get_chat_id::GetChatId;
pub use key::DialogueKey;
pub use storage::*;
use dptree::Handler;
use teloxide_core::types::ChatId;
use std::{fmt::Debug, marker::PhantomData, sync::Arc};
use super::DpHandlerDescription;
mod get_chat_id;
mod key;
mod storage;
const TELOXIDE_DIALOGUE_BEHAVIOUR: &str = "TELOXIDE_DIALOGUE_BEHAVIOUR";
#[derive(Debug)]
pub struct Dialogue<D, S>
where
S: ?Sized,
{
storage: Arc<S>,
key: DialogueKey,
_phantom: PhantomData<D>,
}
impl<D, S> Clone for Dialogue<D, S>
where
S: ?Sized,
{
fn clone(&self) -> Self {
Dialogue { storage: self.storage.clone(), key: self.key.clone(), _phantom: PhantomData }
}
}
impl<D, S> Dialogue<D, S>
where
D: Send + 'static,
S: Storage<D> + ?Sized,
{
#[must_use]
pub fn new(storage: Arc<S>, key: impl Into<DialogueKey>) -> Self {
Self { storage, key: key.into(), _phantom: PhantomData }
}
#[must_use]
pub fn chat_id(&self) -> ChatId {
self.key.chat_id
}
#[must_use]
pub fn key(&self) -> &DialogueKey {
&self.key
}
pub async fn get(&self) -> Result<Option<D>, S::Error> {
self.storage.clone().get_dialogue(self.key.clone()).await
}
pub async fn get_or_default(&self) -> Result<D, S::Error>
where
D: Default,
{
self.storage.clone().get_or_insert_dialogue(self.key.clone(), D::default, false).await
}
pub async fn update<State>(&self, state: State) -> Result<(), S::Error>
where
D: From<State>,
{
let new_dialogue = state.into();
self.storage.clone().update_dialogue(self.key.clone(), new_dialogue).await?;
Ok(())
}
pub async fn reset(&self) -> Result<(), S::Error>
where
D: Default,
{
self.update(D::default()).await
}
pub async fn exit(&self) -> Result<(), S::Error> {
self.storage.clone().remove_dialogue(self.key.clone()).await
}
}
#[must_use]
pub fn enter<Upd, S, D, Output>() -> Handler<'static, Output, DpHandlerDescription>
where
S: Storage<D> + ?Sized + Send + Sync + 'static,
<S as Storage<D>>::Error: Debug + Send,
D: Default + Clone + Send + Sync + 'static,
Upd: GetChatId + Clone + Send + Sync + 'static,
Output: Send + Sync + 'static,
{
dptree::filter_map(|storage: Arc<S>, upd: Upd| {
Some(Dialogue::new(storage, upd.dialogue_key()?))
})
.filter_map_async(|dialogue: Dialogue<D, S>| async move {
let behaviour = std::env::var(TELOXIDE_DIALOGUE_BEHAVIOUR);
let reset_incompatible = behaviour.as_deref() == Ok("default");
match dialogue
.storage
.get_or_insert_dialogue(dialogue.key, D::default, reset_incompatible)
.await
{
Ok(state) => Some(state),
Err(err) => {
if !matches!(behaviour.as_deref(), Ok("default" | "panic") | Err(_)) {
panic!("`TELOXIDE_DIALOGUE_BEHAVIOUR` should be one of: default/panic");
}
log::error!("could not load dialogue state: {err:?}");
None
}
}
})
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
#[derive(Clone, Debug, PartialEq, Eq)]
struct State(usize);
static DEFAULTS: AtomicUsize = AtomicUsize::new(0);
impl Default for State {
fn default() -> Self {
Self(DEFAULTS.fetch_add(1, Ordering::Relaxed))
}
}
#[tokio::test]
async fn concurrent_get_or_default_returns_the_stored_state() {
let dialogue = Dialogue::new(InMemStorage::new(), ChatId(42));
let (one, two) = tokio::join!(dialogue.get_or_default(), dialogue.get_or_default());
assert_eq!(one.unwrap(), State(0));
assert_eq!(two.unwrap(), State(0));
assert_eq!(dialogue.get().await.unwrap(), Some(State(0)));
assert_eq!(DEFAULTS.load(Ordering::Relaxed), 1);
}
}