Skip to main content

teloxide/dispatching/dialogue/storage/
trace_storage.rs

1use std::{collections::HashSet, fmt::Debug, sync::Arc};
2
3use super::{DialogueKey, Storage, StorageKeys};
4use futures::future::BoxFuture;
5
6/// A dialogue storage wrapper which logs all actions performed on an underlying
7/// storage.
8///
9/// Reports about any dialogue action via [`log::Level::Trace`].
10pub struct TraceStorage<S> {
11    inner: Arc<S>,
12}
13
14impl<S> TraceStorage<S> {
15    #[must_use = "This function is pure, that is does nothing unless its output is used"]
16    pub fn new(inner: Arc<S>) -> Arc<Self> {
17        Arc::new(Self { inner })
18    }
19
20    #[must_use = "This function is pure, that is does nothing unless its output is used"]
21    pub fn into_inner(self) -> Arc<S> {
22        self.inner
23    }
24}
25
26impl<S, D> Storage<D> for TraceStorage<S>
27where
28    D: Debug,
29    S: Storage<D> + Send + Sync + 'static,
30{
31    type Error = <S as Storage<D>>::Error;
32
33    fn remove_dialogue(
34        self: Arc<Self>,
35        key: DialogueKey,
36    ) -> BoxFuture<'static, Result<(), Self::Error>>
37    where
38        D: Send + 'static,
39    {
40        log::trace!("Removing dialogue {key:?}");
41        self.inner.clone().remove_dialogue(key)
42    }
43
44    fn update_dialogue(
45        self: Arc<Self>,
46        key: DialogueKey,
47        dialogue: D,
48    ) -> BoxFuture<'static, Result<(), Self::Error>>
49    where
50        D: Send + 'static,
51    {
52        Box::pin(async move {
53            let to = format!("{dialogue:#?}");
54            self.inner.clone().update_dialogue(key.clone(), dialogue).await?;
55            log::trace!("Updated dialogue {key:?}: {to:#?}");
56            Ok(())
57        })
58    }
59
60    fn get_dialogue(
61        self: Arc<Self>,
62        key: DialogueKey,
63    ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
64        log::trace!("Requested dialogue {key:?}");
65        self.inner.clone().get_dialogue(key)
66    }
67
68    fn get_or_insert_dialogue(
69        self: Arc<Self>,
70        key: DialogueKey,
71        default: fn() -> D,
72        reset_incompatible: bool,
73    ) -> BoxFuture<'static, Result<D, Self::Error>> {
74        log::trace!("Requested or initialized dialogue {key:?}");
75        self.inner.clone().get_or_insert_dialogue(key, default, reset_incompatible)
76    }
77}
78
79impl<S: StorageKeys + Send + Sync + 'static> StorageKeys for TraceStorage<S> {
80    type Error = S::Error;
81
82    fn keys(self: Arc<Self>) -> BoxFuture<'static, Result<HashSet<DialogueKey>, Self::Error>> {
83        log::trace!("Requested keys");
84        self.inner.clone().keys()
85    }
86}