teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use super::UpdateHandler;

use dptree::{
    di::{Asyncify, Injectable},
    prelude::DependencyMap,
    HandlerSignature,
};
use std::{collections::BTreeSet, sync::Arc};
use tracing::{Instrument, Span};

pub trait UpdateHandlerTracingExt<E> {
    /// Returns an `UpdateHandler` wrapped in an async span.
    fn instrument_with_async<F, FnArgs>(self, f: F) -> Self
    where
        F: Injectable<Span, FnArgs> + Send + Sync + 'static;

    /// Returns an `UpdateHandler` wrapped in a span.
    fn instrument_with<F, FnArgs>(self, f: F) -> Self
    where
        Asyncify<F>: Injectable<Span, FnArgs> + Send + Sync + 'static;
}

impl<E: 'static> UpdateHandlerTracingExt<E> for UpdateHandler<E> {
    fn instrument_with_async<F, FnArgs>(self, f: F) -> UpdateHandler<E>
    where
        F: Injectable<Span, FnArgs> + Send + Sync + 'static,
    {
        let mut signature = self.sig().clone();
        let span_obligations = F::obligations();
        match &mut signature {
            HandlerSignature::Other { obligations, .. } => {
                for (ty, location) in span_obligations {
                    obligations.entry(ty).or_insert(location);
                }
            }
            // An instrumented entry is no longer an inert entry: it runs
            // user code, so it can be composed as a normal continuing handler.
            HandlerSignature::Entry => {
                signature = HandlerSignature::Other {
                    obligations: span_obligations,
                    guaranteed_outcomes: BTreeSet::new(),
                    conditional_outcomes: BTreeSet::new(),
                    continues: true,
                };
            }
        }
        let f = Arc::new(f);

        dptree::from_fn_with_description(
            self.description().clone(),
            move |deps: DependencyMap, cont| {
                let self_c = self.clone();
                let f = Arc::clone(&f);

                async move {
                    let f = f.inject(&deps);
                    let span = f().await;
                    drop(f);

                    self_c.execute(deps, cont).instrument(span).await
                }
            },
            signature,
        )
    }

    fn instrument_with<F, FnArgs>(self, f: F) -> Self
    where
        Asyncify<F>: Injectable<Span, FnArgs> + Send + Sync + 'static,
    {
        self.instrument_with_async(Asyncify(f))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dptree::{deps, Type};

    #[tokio::test]
    async fn instrumented_endpoint_keeps_handler_and_span_dependencies() {
        let handler: UpdateHandler<u8> = dptree::endpoint(|value: u8| async move { Err(value) });
        let instrumented = handler.instrument_with(|_: bool| Span::none());
        let HandlerSignature::Other { obligations, continues, .. } = instrumented.sig() else {
            panic!("expected an endpoint signature");
        };
        assert_eq!(
            obligations.keys().copied().collect::<BTreeSet<_>>(),
            [Type::of::<u8>(), Type::of::<bool>()].into()
        );
        assert!(!continues);
        assert_eq!(instrumented.dispatch(deps![3u8, true]).await.break_value(), Some(Err(3)));
    }

    #[test]
    fn instrumented_map_keeps_outputs() {
        let handler: UpdateHandler<()> = dptree::map(|value: u8| value != 0);
        let expected = handler.sig().clone();
        assert_eq!(handler.instrument_with(Span::none).sig(), &expected);
    }
}