Skip to main content

teloxide/dispatching/
dispatcher.rs

1use crate::{
2    dispatching::{
3        distribution::default_distribution_function, DefaultKey, DpHandlerDescription,
4        ShutdownToken,
5    },
6    error_handlers::{ErrorHandler, LoggingErrorHandler},
7    requests::{Request, Requester},
8    stop::StopToken,
9    types::{Update, UpdateKind},
10    update_listeners::{self, UpdateListener},
11};
12
13use dptree::di::DependencyMap;
14use either::Either;
15use futures::{
16    future::{self, BoxFuture},
17    stream::FuturesUnordered,
18    FutureExt as _, StreamExt as _,
19};
20use tokio_stream::wrappers::ReceiverStream;
21
22use std::{
23    collections::HashMap,
24    fmt::Debug,
25    future::Future,
26    hash::Hash,
27    ops::{ControlFlow, Deref},
28    pin::pin,
29    sync::{
30        atomic::{AtomicBool, AtomicU32, Ordering},
31        Arc,
32    },
33};
34
35/// The builder for [`Dispatcher`].
36///
37/// See also: ["Dispatching or
38/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
39pub struct DispatcherBuilder<R, Err, Key> {
40    bot: R,
41    dependencies: DependencyMap,
42    handler: Arc<UpdateHandler<Err>>,
43    default_handler: DefaultHandler,
44    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
45    ctrlc_handler: bool,
46    distribution_f: fn(&Update) -> Option<Key>,
47    worker_queue_size: usize,
48}
49
50impl<R, Err, Key> DispatcherBuilder<R, Err, Key>
51where
52    R: Clone + Requester + Clone + Send + Sync + 'static,
53    Err: Debug + Send + Sync + 'static,
54{
55    /// Specifies a handler that will be called for an unhandled update.
56    ///
57    /// By default, it is a mere [`log::warn`].
58    #[must_use]
59    pub fn default_handler<H, Fut>(self, handler: H) -> Self
60    where
61        H: Fn(Arc<Update>) -> Fut + Send + Sync + 'static,
62        Fut: Future<Output = ()> + Send + 'static,
63    {
64        let handler = Arc::new(handler);
65
66        Self {
67            default_handler: Arc::new(move |upd| {
68                let handler = Arc::clone(&handler);
69                Box::pin(handler(upd))
70            }),
71            ..self
72        }
73    }
74
75    /// Specifies a handler that will be called on a handler error.
76    ///
77    /// Its dependency map contains the dependencies available before
78    /// dispatching the update, including the bot, [`crate::types::Me`] and
79    /// the current [`Update`]. Values added by the handler tree are not
80    /// included.
81    ///
82    /// By default, it is [`LoggingErrorHandler`].
83    #[must_use]
84    pub fn error_handler(self, handler: Arc<dyn ErrorHandler<Err> + Send + Sync>) -> Self {
85        Self { error_handler: handler, ..self }
86    }
87
88    /// Specifies dependencies that can be used inside of handlers.
89    ///
90    /// By default, there is no dependencies.
91    #[must_use]
92    pub fn dependencies(self, dependencies: DependencyMap) -> Self {
93        Self { dependencies, ..self }
94    }
95
96    /// Enables the `^C` handler that [`shutdown`]s dispatching.
97    ///
98    /// [`shutdown`]: ShutdownToken::shutdown
99    #[cfg(feature = "ctrlc_handler")]
100    #[must_use]
101    pub fn enable_ctrlc_handler(self) -> Self {
102        Self { ctrlc_handler: true, ..self }
103    }
104
105    /// Specifies size of the queue for workers.
106    ///
107    /// By default it's 64.
108    #[must_use]
109    pub fn worker_queue_size(self, size: usize) -> Self {
110        Self { worker_queue_size: size, ..self }
111    }
112
113    /// Specifies the stack size available to the dispatcher.
114    ///
115    /// By default, it's 8 * 1024 * 1024 bytes (8 MiB).
116    #[must_use]
117    #[deprecated(since = "0.15.0", note = "This method is a no-op; you can just remove it.")]
118    pub fn stack_size(self, _size: usize) -> Self {
119        self
120    }
121
122    /// Specifies the distribution function that decides how updates are grouped
123    /// before execution.
124    ///
125    /// ## Update grouping
126    ///
127    /// When [`Dispatcher`] receives updates, it runs dispatching tree
128    /// (handlers) concurrently. This means that multiple updates can be
129    /// processed at the same time.
130    ///
131    /// However, this is not always convenient. For example, if you have global
132    /// state, then you may want to process some updates sequentially, to
133    /// prevent state inconsistencies.
134    ///
135    /// This is why `teloxide` allows grouping updates. Updates for which the
136    /// distribution function `f` returns the same "distribution key" `K` will
137    /// be run in sequence (while still being processed concurrently with the
138    /// updates with different distribution keys).
139    ///
140    /// Updates for which `f` returns `None` will always be processed in
141    /// parallel.
142    ///
143    /// ## Default distribution function
144    ///
145    /// By default the distribution function is equivalent to `|upd|
146    /// upd.chat().map(|chat| chat.id)`, so updates from the same chat will be
147    /// processed sequentially.
148    ///
149    /// This pair nicely with dialogue system, which has state attached to
150    /// chats.
151    ///
152    /// ## Examples
153    ///
154    /// Grouping updates by user who caused this update to happen:
155    ///
156    /// ```
157    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
158    ///
159    /// let bot = Bot::new("TOKEN");
160    /// let handler = dptree::entry() /* ... */;
161    /// let dp = Dispatcher::builder(bot, handler)
162    ///     .distribution_function(|upd| upd.from().map(|user| user.id))
163    ///     .build();
164    /// # let _: Dispatcher<_, (), _> = dp;
165    /// ```
166    ///
167    /// Not grouping updates at all, always processing updates concurrently:
168    ///
169    /// ```
170    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
171    ///
172    /// let bot = Bot::new("TOKEN");
173    /// let handler = dptree::entry() /* ... */;
174    /// let dp = Dispatcher::builder(bot, handler).distribution_function(|_| None::<()>).build();
175    /// # let _: Dispatcher<_, (), _> = dp;
176    /// ```
177    #[must_use]
178    pub fn distribution_function<K>(
179        self,
180        f: fn(&Update) -> Option<K>,
181    ) -> DispatcherBuilder<R, Err, K>
182    where
183        K: Hash + Eq,
184    {
185        let Self {
186            bot,
187            dependencies,
188            handler,
189            default_handler,
190            error_handler,
191            ctrlc_handler,
192            distribution_f: _,
193            worker_queue_size,
194        } = self;
195
196        DispatcherBuilder {
197            bot,
198            dependencies,
199            handler,
200            default_handler,
201            error_handler,
202            ctrlc_handler,
203            distribution_f: f,
204            worker_queue_size,
205        }
206    }
207
208    /// Constructs [`Dispatcher`].
209    ///
210    /// ## Panics
211    /// This function will panic at run-time if [`dptree`] fails to type-check
212    /// the provided handler. An appropriate error message will be emitted.
213    #[must_use]
214    pub fn build(self) -> Dispatcher<R, Err, Key> {
215        let Self {
216            bot,
217            dependencies,
218            handler,
219            default_handler,
220            error_handler,
221            distribution_f,
222            worker_queue_size,
223            ctrlc_handler,
224        } = self;
225
226        dptree::type_check(
227            handler.sig(),
228            &dependencies,
229            &[
230                dptree::Type::of::<R>(),
231                dptree::Type::of::<teloxide_core::types::Update>(),
232                dptree::Type::of::<teloxide_core::types::BotFullInfo>(),
233            ],
234        );
235
236        // If the `ctrlc_handler` feature is not enabled, don't emit a warning.
237        let _ = ctrlc_handler;
238
239        let dp = Dispatcher {
240            bot,
241            dependencies,
242            handler,
243            default_handler,
244            error_handler,
245            state: ShutdownToken::new(),
246            distribution_f,
247            worker_queue_size,
248            workers: HashMap::new(),
249            default_worker: None,
250            current_number_of_active_workers: Default::default(),
251            max_number_of_active_workers: Default::default(),
252        };
253
254        #[cfg(feature = "ctrlc_handler")]
255        {
256            if ctrlc_handler {
257                let mut dp = dp;
258                dp.setup_ctrlc_handler_inner();
259                return dp;
260            }
261        }
262
263        dp
264    }
265}
266
267/// The base for update dispatching.
268///
269/// ## Update grouping
270///
271/// `Dispatcher` generally processes updates concurrently. However, by default,
272/// updates from the same chat are processed sequentially. Learn more about
273/// [update grouping].
274///
275/// See also: ["Dispatching or
276/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
277///
278/// [update grouping]: DispatcherBuilder#update-grouping
279pub struct Dispatcher<R, Err, Key> {
280    bot: R,
281    dependencies: DependencyMap,
282
283    handler: Arc<UpdateHandler<Err>>,
284    default_handler: DefaultHandler,
285
286    distribution_f: fn(&Update) -> Option<Key>,
287    worker_queue_size: usize,
288    current_number_of_active_workers: Arc<AtomicU32>,
289    max_number_of_active_workers: Arc<AtomicU32>,
290    // Tokio TX channel parts associated with chat IDs that consume updates sequentially.
291    workers: HashMap<Key, Worker>,
292    // The default TX part that consume updates concurrently.
293    default_worker: Option<Worker>,
294
295    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
296
297    state: ShutdownToken,
298}
299
300struct Worker {
301    tx: tokio::sync::mpsc::Sender<Update>,
302    handle: tokio::task::JoinHandle<()>,
303    is_waiting: Arc<AtomicBool>,
304}
305
306// TODO: it is allowed to return message as response on telegram request in
307// webhooks, so we can allow this too. See more there: https://core.telegram.org/bots/api#making-requests-when-getting-updates
308
309/// A handler that processes updates from Telegram.
310pub type UpdateHandler<Err> = dptree::Handler<'static, Result<(), Err>, DpHandlerDescription>;
311
312type DefaultHandler = Arc<dyn Fn(Arc<Update>) -> BoxFuture<'static, ()> + Send + Sync>;
313
314impl<R, Err> Dispatcher<R, Err, DefaultKey>
315where
316    R: Requester + Clone + Send + Sync + 'static,
317    Err: Send + Sync + 'static,
318{
319    /// Constructs a new [`DispatcherBuilder`] with `bot` and `handler`.
320    #[must_use]
321    pub fn builder(bot: R, handler: UpdateHandler<Err>) -> DispatcherBuilder<R, Err, DefaultKey>
322    where
323        Err: Debug,
324    {
325        const DEFAULT_WORKER_QUEUE_SIZE: usize = 64;
326
327        DispatcherBuilder {
328            bot,
329            dependencies: DependencyMap::new(),
330            handler: Arc::new(handler),
331            default_handler: Arc::new(|upd| {
332                log::warn!("Unhandled update: {upd:?}");
333                Box::pin(async {})
334            }),
335            error_handler: LoggingErrorHandler::new(),
336            ctrlc_handler: false,
337            worker_queue_size: DEFAULT_WORKER_QUEUE_SIZE,
338            distribution_f: default_distribution_function,
339        }
340    }
341}
342
343impl<R, Err, Key> Dispatcher<R, Err, Key>
344where
345    R: Requester + Clone + Send + Sync + 'static,
346    Err: Send + Sync + 'static,
347    Key: Hash + Eq + Clone + Send,
348{
349    /// Starts your bot with the default parameters.
350    ///
351    /// The default parameters are a long polling update listener and log all
352    /// errors produced by this listener.
353    ///
354    /// Each time a handler is invoked, [`Dispatcher`] adds the following
355    /// dependencies (in addition to those passed to
356    /// [`DispatcherBuilder::dependencies`]):
357    ///
358    ///  - Your bot passed to [`Dispatcher::builder`];
359    ///  - An update from Telegram;
360    ///  - [`crate::types::BotFullInfo`] (can be used in
361    ///    [`HandlerExt::filter_command`]).
362    ///
363    /// [`HandlerExt::filter_command`]: crate::dispatching::HandlerExt::filter_command
364    pub async fn dispatch(&mut self)
365    where
366        R: Requester + Clone,
367        <R as Requester>::GetUpdates: Send,
368    {
369        let listener = update_listeners::polling_default(self.bot.clone()).await;
370        let error_handler =
371            LoggingErrorHandler::with_custom_text("An error from the update listener");
372
373        self.dispatch_with_listener(listener, error_handler).await;
374    }
375
376    /// Starts your bot with custom `update_listener` and
377    /// `update_listener_error_handler`.
378    ///
379    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
380    /// The listener error handler receives those initial dependencies, but
381    /// there is no current update when receiving an update fails.
382    pub async fn dispatch_with_listener<'a, UListener, Eh>(
383        &'a mut self,
384        update_listener: UListener,
385        update_listener_error_handler: Arc<Eh>,
386    ) where
387        UListener: UpdateListener + Send + 'a,
388        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
389        UListener::Err: Debug,
390    {
391        self.try_dispatch_with_listener(update_listener, update_listener_error_handler)
392            .await
393            .expect("Couldn't prepare dispatching context")
394    }
395
396    /// Same as `dispatch_with_listener` but returns a `Err(_)` instead of
397    /// panicking when the initial telegram api call (`get_me`) fails.
398    ///
399    /// Starts your bot with custom `update_listener` and
400    /// `update_listener_error_handler`.
401    ///
402    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
403    pub async fn try_dispatch_with_listener<'a, UListener, Eh>(
404        &'a mut self,
405        mut update_listener: UListener,
406        update_listener_error_handler: Arc<Eh>,
407    ) -> Result<(), R::Err>
408    where
409        UListener: UpdateListener + Send + 'a,
410        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
411        UListener::Err: Debug,
412    {
413        // FIXME: there should be a way to check if dependency is already inserted
414        let me = self.bot.get_me().send().await?;
415        self.dependencies.insert(me);
416        self.dependencies.insert(self.bot.clone());
417
418        let description = self.handler.description();
419        let allowed_updates = description.allowed_updates();
420        log::debug!("hinting allowed updates: {allowed_updates:?}");
421        update_listener.hint_allowed_updates(&mut allowed_updates.into_iter());
422
423        let stop_token = Some(update_listener.stop_token());
424        self.start_listening(update_listener, update_listener_error_handler, stop_token).await;
425
426        Ok(())
427    }
428
429    async fn start_listening<'a, UListener, Eh>(
430        &'a mut self,
431        mut update_listener: UListener,
432        update_listener_error_handler: Arc<Eh>,
433        mut stop_token: Option<StopToken>,
434    ) where
435        UListener: UpdateListener + 'a,
436        Eh: ErrorHandler<UListener::Err> + 'a,
437        UListener::Err: Debug,
438    {
439        self.state.start_dispatching();
440
441        let stream = update_listener.as_stream();
442        tokio::pin!(stream);
443
444        loop {
445            self.remove_inactive_workers_if_needed().await;
446
447            let res = future::select(stream.next(), pin!(self.state.wait_for_changes()))
448                .map(either)
449                .await
450                .map_either(|l| l.0, |r| r.0);
451
452            match res {
453                Either::Left(upd) => match upd {
454                    Some(upd) => self.process_update(upd, &update_listener_error_handler).await,
455                    None => break,
456                },
457                Either::Right(()) => {
458                    if self.state.is_shutting_down() {
459                        if let Some(token) = stop_token.take() {
460                            log::debug!("Start shutting down dispatching...");
461                            token.stop();
462                        }
463                    }
464                }
465            }
466        }
467
468        self.workers
469            .drain()
470            .map(|(_chat_id, worker)| worker.handle)
471            .chain(self.default_worker.take().map(|worker| worker.handle))
472            .collect::<FuturesUnordered<_>>()
473            .for_each(|res| async {
474                res.expect("Failed to wait for a worker.");
475            })
476            .await;
477
478        self.state.done();
479    }
480
481    async fn process_update<LErr, LErrHandler>(
482        &mut self,
483        update: Result<Update, LErr>,
484        err_handler: &Arc<LErrHandler>,
485    ) where
486        LErrHandler: ErrorHandler<LErr>,
487    {
488        match update {
489            Ok(upd) => {
490                if let UpdateKind::Error(err) = upd.kind {
491                    log::error!(
492                        "Cannot parse an update.\nError: {err:?}\n\
493                            This is a bug in teloxide-core, please open an issue here: \
494                            https://github.com/teloxide/teloxide/issues.",
495                    );
496                    return;
497                }
498
499                let worker = match (self.distribution_f)(&upd) {
500                    Some(key) => self.workers.entry(key).or_insert_with(|| {
501                        let deps = self.dependencies.clone();
502                        let handler = Arc::clone(&self.handler);
503                        let default_handler = Arc::clone(&self.default_handler);
504                        let error_handler = Arc::clone(&self.error_handler);
505
506                        spawn_worker(
507                            deps,
508                            handler,
509                            default_handler,
510                            error_handler,
511                            Arc::clone(&self.current_number_of_active_workers),
512                            Arc::clone(&self.max_number_of_active_workers),
513                            self.worker_queue_size,
514                        )
515                    }),
516                    None => self.default_worker.get_or_insert_with(|| {
517                        let deps = self.dependencies.clone();
518                        let handler = Arc::clone(&self.handler);
519                        let default_handler = Arc::clone(&self.default_handler);
520                        let error_handler = Arc::clone(&self.error_handler);
521
522                        spawn_default_worker(
523                            deps,
524                            handler,
525                            default_handler,
526                            error_handler,
527                            self.worker_queue_size,
528                        )
529                    }),
530                };
531
532                worker.tx.send(upd).await.expect("TX is dead");
533            }
534            Err(err) => err_handler.clone().handle_error(err, self.dependencies.clone()).await,
535        }
536    }
537
538    async fn remove_inactive_workers_if_needed(&mut self) {
539        let workers = self.workers.len();
540        let max = self.max_number_of_active_workers.load(Ordering::Relaxed) as usize;
541
542        if workers <= max {
543            return;
544        }
545
546        self.remove_inactive_workers().await;
547    }
548
549    #[inline(never)] // Cold function.
550    async fn remove_inactive_workers(&mut self) {
551        let handles = self
552            .workers
553            .iter()
554            .filter(|(_, worker)| {
555                worker.tx.capacity() == self.worker_queue_size
556                    && worker.is_waiting.load(Ordering::Relaxed)
557            })
558            .map(|(k, _)| k)
559            .cloned()
560            .collect::<Vec<_>>()
561            .into_iter()
562            .map(|key| {
563                let Worker { tx, handle, .. } = self.workers.remove(&key).unwrap();
564
565                // Close channel, worker should stop almost immediately
566                // (it's been supposedly waiting on the channel)
567                drop(tx);
568
569                handle
570            });
571
572        for handle in handles {
573            // We must wait for worker to stop anyway, even though it should stop
574            // immediately. This helps in case if we've checked that the worker
575            // is waiting in between it received the update and set the flag.
576            let _ = handle.await;
577        }
578    }
579
580    /// Returns a shutdown token, which can later be used to
581    /// [`ShutdownToken::shutdown`].
582    pub fn shutdown_token(&self) -> ShutdownToken {
583        self.state.clone()
584    }
585}
586
587impl<R, Err, Key> Dispatcher<R, Err, Key> {
588    #[cfg(feature = "ctrlc_handler")]
589    fn setup_ctrlc_handler_inner(&mut self) {
590        let token = self.state.clone();
591        tokio::spawn(async move {
592            loop {
593                tokio::signal::ctrl_c().await.expect("Failed to listen for ^C");
594
595                match token.shutdown() {
596                    Ok(f) => {
597                        log::info!("^C received, trying to shutdown the dispatcher...");
598                        f.await;
599                        log::info!("dispatcher is shutdown...");
600                    }
601                    Err(_) => {
602                        log::info!("^C received, the dispatcher isn't running, ignoring the signal")
603                    }
604                }
605            }
606        });
607    }
608}
609
610fn spawn_worker<Err>(
611    deps: DependencyMap,
612    handler: Arc<UpdateHandler<Err>>,
613    default_handler: DefaultHandler,
614    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
615    current_number_of_active_workers: Arc<AtomicU32>,
616    max_number_of_active_workers: Arc<AtomicU32>,
617    queue_size: usize,
618) -> Worker
619where
620    Err: Send + Sync + 'static,
621{
622    let (tx, mut rx) = tokio::sync::mpsc::channel(queue_size);
623    let is_waiting = Arc::new(AtomicBool::new(true));
624    let is_waiting_local = Arc::clone(&is_waiting);
625
626    let deps = Arc::new(deps);
627
628    let handle = tokio::spawn(async move {
629        while let Some(update) = rx.recv().await {
630            is_waiting_local.store(false, Ordering::Relaxed);
631            {
632                let current = current_number_of_active_workers.fetch_add(1, Ordering::Relaxed) + 1;
633                max_number_of_active_workers.fetch_max(current, Ordering::Relaxed);
634            }
635
636            let deps = Arc::clone(&deps);
637            let handler = Arc::clone(&handler);
638            let default_handler = Arc::clone(&default_handler);
639            let error_handler = Arc::clone(&error_handler);
640
641            handle_update(update, deps, handler, default_handler, error_handler).await;
642
643            current_number_of_active_workers.fetch_sub(1, Ordering::Relaxed);
644            is_waiting_local.store(true, Ordering::Relaxed);
645        }
646    });
647
648    Worker { tx, handle, is_waiting }
649}
650
651fn spawn_default_worker<Err>(
652    deps: DependencyMap,
653    handler: Arc<UpdateHandler<Err>>,
654    default_handler: DefaultHandler,
655    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
656    queue_size: usize,
657) -> Worker
658where
659    Err: Send + Sync + 'static,
660{
661    let (tx, rx) = tokio::sync::mpsc::channel(queue_size);
662
663    let deps = Arc::new(deps);
664
665    let handle = tokio::spawn(ReceiverStream::new(rx).for_each_concurrent(None, move |update| {
666        let deps = Arc::clone(&deps);
667        let handler = Arc::clone(&handler);
668        let default_handler = Arc::clone(&default_handler);
669        let error_handler = Arc::clone(&error_handler);
670
671        handle_update(update, deps, handler, default_handler, error_handler)
672    }));
673
674    Worker { tx, handle, is_waiting: Arc::new(AtomicBool::new(true)) }
675}
676
677async fn handle_update<Err>(
678    update: Update,
679    deps: Arc<DependencyMap>,
680    handler: Arc<UpdateHandler<Err>>,
681    default_handler: DefaultHandler,
682    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
683) where
684    Err: Send + Sync + 'static,
685{
686    let mut deps = deps.deref().clone();
687    deps.insert(update);
688
689    match handler.dispatch(deps.clone()).await {
690        ControlFlow::Break(Ok(())) => {}
691        ControlFlow::Break(Err(err)) => error_handler.handle_error(err, deps).await,
692        ControlFlow::Continue(deps) => {
693            let update = deps.get();
694            (default_handler)(update).await;
695        }
696    }
697}
698
699fn either<L, R>(x: future::Either<L, R>) -> Either<L, R> {
700    match x {
701        future::Either::Left(l) => Either::Left(l),
702        future::Either::Right(r) => Either::Right(r),
703    }
704}
705#[cfg(test)]
706mod tests {
707    use std::convert::Infallible;
708
709    use teloxide_core::Bot;
710
711    use super::*;
712
713    #[tokio::test]
714    async fn handler_error_receives_initial_dependencies() {
715        let initial = dptree::deps!["configured"];
716        let handler = dptree::map(|| 42_u32).endpoint(|| async { Err("handler failed") });
717        let update = Update {
718            id: crate::types::UpdateId(1),
719            kind: UpdateKind::Error(serde_json::Value::Null),
720        };
721        let (tx, rx) = tokio::sync::oneshot::channel();
722        let tx = std::sync::Mutex::new(Some(tx));
723        let error_handler = move |err, deps: DependencyMap| {
724            let tx = tx.lock().unwrap().take().unwrap();
725            async move { tx.send((err, deps)).unwrap() }
726        };
727
728        handle_update(
729            update,
730            Arc::new(initial),
731            Arc::new(handler),
732            Arc::new(|_| unreachable!()),
733            Arc::new(error_handler),
734        )
735        .await;
736
737        let (err, deps) = rx.await.unwrap();
738        assert_eq!(err, "handler failed");
739        assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
740        assert_eq!(deps.try_get::<Update>().unwrap().id, crate::types::UpdateId(1));
741        assert!(deps.try_get::<u32>().is_none());
742    }
743
744    #[tokio::test]
745    async fn listener_error_receives_initial_dependencies_without_current_update() {
746        let mut dispatcher = Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
747            .dependencies(dptree::deps!["configured"])
748            .build();
749        let error_handler = Arc::new(|err, deps: DependencyMap| async move {
750            assert_eq!(err, "listener failed");
751            assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
752            assert!(deps.try_get::<Update>().is_none());
753        });
754        dispatcher.process_update(Err("listener failed"), &error_handler).await;
755    }
756
757    #[tokio::test]
758    async fn test_tokio_spawn() {
759        tokio::spawn(async {
760            // Just check that this code compiles.
761            if false {
762                Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
763                    .build()
764                    .dispatch()
765                    .await;
766            }
767        })
768        .await
769        .unwrap();
770    }
771}