teloxide/dispatching/
tracing.rs1use super::UpdateHandler;
2
3use dptree::{
4 di::{Asyncify, Injectable},
5 prelude::DependencyMap,
6 HandlerSignature,
7};
8use std::{collections::BTreeSet, sync::Arc};
9use tracing::{Instrument, Span};
10
11pub trait UpdateHandlerTracingExt<E> {
12 fn instrument_with_async<F, FnArgs>(self, f: F) -> Self
14 where
15 F: Injectable<Span, FnArgs> + Send + Sync + 'static;
16
17 fn instrument_with<F, FnArgs>(self, f: F) -> Self
19 where
20 Asyncify<F>: Injectable<Span, FnArgs> + Send + Sync + 'static;
21}
22
23impl<E: 'static> UpdateHandlerTracingExt<E> for UpdateHandler<E> {
24 fn instrument_with_async<F, FnArgs>(self, f: F) -> UpdateHandler<E>
25 where
26 F: Injectable<Span, FnArgs> + Send + Sync + 'static,
27 {
28 let mut signature = self.sig().clone();
29 let span_obligations = F::obligations();
30 match &mut signature {
31 HandlerSignature::Other { obligations, .. } => {
32 for (ty, location) in span_obligations {
33 obligations.entry(ty).or_insert(location);
34 }
35 }
36 HandlerSignature::Entry => {
39 signature = HandlerSignature::Other {
40 obligations: span_obligations,
41 guaranteed_outcomes: BTreeSet::new(),
42 conditional_outcomes: BTreeSet::new(),
43 continues: true,
44 };
45 }
46 }
47 let f = Arc::new(f);
48
49 dptree::from_fn_with_description(
50 self.description().clone(),
51 move |deps: DependencyMap, cont| {
52 let self_c = self.clone();
53 let f = Arc::clone(&f);
54
55 async move {
56 let f = f.inject(&deps);
57 let span = f().await;
58 drop(f);
59
60 self_c.execute(deps, cont).instrument(span).await
61 }
62 },
63 signature,
64 )
65 }
66
67 fn instrument_with<F, FnArgs>(self, f: F) -> Self
68 where
69 Asyncify<F>: Injectable<Span, FnArgs> + Send + Sync + 'static,
70 {
71 self.instrument_with_async(Asyncify(f))
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78 use dptree::{deps, Type};
79
80 #[tokio::test]
81 async fn instrumented_endpoint_keeps_handler_and_span_dependencies() {
82 let handler: UpdateHandler<u8> = dptree::endpoint(|value: u8| async move { Err(value) });
83 let instrumented = handler.instrument_with(|_: bool| Span::none());
84 let HandlerSignature::Other { obligations, continues, .. } = instrumented.sig() else {
85 panic!("expected an endpoint signature");
86 };
87 assert_eq!(
88 obligations.keys().copied().collect::<BTreeSet<_>>(),
89 [Type::of::<u8>(), Type::of::<bool>()].into()
90 );
91 assert!(!continues);
92 assert_eq!(instrumented.dispatch(deps![3u8, true]).await.break_value(), Some(Err(3)));
93 }
94
95 #[test]
96 fn instrumented_map_keeps_outputs() {
97 let handler: UpdateHandler<()> = dptree::map(|value: u8| value != 0);
98 let expected = handler.sig().clone();
99 assert_eq!(handler.instrument_with(Span::none).sig(), &expected);
100 }
101}