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    types::{Update, UpdateKind},
9    update_listeners::{self, UpdateListener},
10};
11
12use dptree::di::DependencyMap;
13use futures::{future::BoxFuture, stream::FuturesUnordered, FutureExt as _, StreamExt as _};
14use tokio::{
15    sync::{mpsc, OwnedSemaphorePermit, Semaphore},
16    task::JoinHandle,
17};
18use tokio_stream::wrappers::ReceiverStream;
19
20use std::{
21    collections::HashMap,
22    fmt::Debug,
23    future::Future,
24    hash::Hash,
25    ops::{ControlFlow, Deref},
26    panic::AssertUnwindSafe,
27    sync::{
28        atomic::{AtomicUsize, Ordering},
29        Arc,
30    },
31};
32
33/// The builder for [`Dispatcher`].
34///
35/// See also: ["Dispatching or
36/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
37pub struct DispatcherBuilder<R, Err, Key> {
38    bot: R,
39    dependencies: DependencyMap,
40    handler: Arc<UpdateHandler<Err>>,
41    default_handler: DefaultHandler,
42    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
43    ctrlc_handler: bool,
44    distribution_f: fn(&Update) -> Option<Key>,
45    worker_queue_size: usize,
46    max_pending_updates: Option<usize>,
47}
48
49impl<R, Err, Key> DispatcherBuilder<R, Err, Key>
50where
51    R: Clone + Requester + Clone + Send + Sync + 'static,
52    Err: Debug + Send + Sync + 'static,
53{
54    /// Specifies a handler that will be called for an unhandled update.
55    ///
56    /// By default, it is a mere [`log::warn`].
57    #[must_use]
58    pub fn default_handler<H, Fut>(self, handler: H) -> Self
59    where
60        H: Fn(Arc<Update>) -> Fut + Send + Sync + 'static,
61        Fut: Future<Output = ()> + Send + 'static,
62    {
63        let handler = Arc::new(handler);
64
65        Self {
66            default_handler: Arc::new(move |upd| {
67                let handler = Arc::clone(&handler);
68                Box::pin(handler(upd))
69            }),
70            ..self
71        }
72    }
73
74    /// Specifies a handler that will be called on a handler error.
75    ///
76    /// Its dependency map contains the dependencies available before
77    /// dispatching the update, including the bot, [`crate::types::Me`] and
78    /// the current [`Update`]. Values added by the handler tree are not
79    /// included.
80    ///
81    /// By default, it is [`LoggingErrorHandler`].
82    #[must_use]
83    pub fn error_handler(self, handler: Arc<dyn ErrorHandler<Err> + Send + Sync>) -> Self {
84        Self { error_handler: handler, ..self }
85    }
86
87    /// Specifies dependencies that can be used inside of handlers.
88    ///
89    /// By default, there is no dependencies.
90    #[must_use]
91    pub fn dependencies(self, dependencies: DependencyMap) -> Self {
92        Self { dependencies, ..self }
93    }
94
95    /// Enables the `^C` handler that [`shutdown`]s dispatching.
96    ///
97    /// [`shutdown`]: ShutdownToken::shutdown
98    #[cfg(feature = "ctrlc_handler")]
99    #[must_use]
100    pub fn enable_ctrlc_handler(self) -> Self {
101        Self { ctrlc_handler: true, ..self }
102    }
103
104    /// Specifies size of the queue for workers.
105    ///
106    /// By default it's 64.
107    #[must_use]
108    pub fn worker_queue_size(self, size: usize) -> Self {
109        Self { worker_queue_size: size, ..self }
110    }
111
112    /// Sets the global maximum number of queued and running updates, across
113    /// both keyed and unkeyed workers. Defaults to the worker queue size.
114    ///
115    /// When all slots are occupied, the dispatcher stops reading updates from
116    /// its listener until a slot becomes available. This includes reading
117    /// buffered updates during graceful shutdown.
118    #[must_use]
119    pub fn max_pending_updates(self, limit: usize) -> Self {
120        Self { max_pending_updates: Some(limit), ..self }
121    }
122
123    /// Specifies the stack size available to the dispatcher.
124    ///
125    /// By default, it's 8 * 1024 * 1024 bytes (8 MiB).
126    #[must_use]
127    #[deprecated(since = "0.15.0", note = "This method is a no-op; you can just remove it.")]
128    pub fn stack_size(self, _size: usize) -> Self {
129        self
130    }
131
132    /// Specifies the distribution function that decides how updates are grouped
133    /// before execution.
134    ///
135    /// ## Update grouping
136    ///
137    /// When [`Dispatcher`] receives updates, it runs dispatching tree
138    /// (handlers) concurrently. This means that multiple updates can be
139    /// processed at the same time.
140    ///
141    /// However, this is not always convenient. For example, if you have global
142    /// state, then you may want to process some updates sequentially, to
143    /// prevent state inconsistencies.
144    ///
145    /// This is why `teloxide` allows grouping updates. Updates for which the
146    /// distribution function `f` returns the same "distribution key" `K` will
147    /// be run in sequence (while still being processed concurrently with the
148    /// updates with different distribution keys).
149    ///
150    /// Updates for which `f` returns `None` can run concurrently, subject to
151    /// [`Self::max_pending_updates`].
152    ///
153    /// ## Default distribution function
154    ///
155    /// By default the distribution function is equivalent to `|upd|
156    /// upd.chat().map(|chat| chat.id)`, so updates from the same chat will be
157    /// processed sequentially.
158    ///
159    /// This pair nicely with dialogue system, which has state attached to
160    /// chats.
161    ///
162    /// ## Examples
163    ///
164    /// Grouping updates by user who caused this update to happen:
165    ///
166    /// ```
167    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
168    ///
169    /// let bot = Bot::new("TOKEN");
170    /// let handler = dptree::entry() /* ... */;
171    /// let dp = Dispatcher::builder(bot, handler)
172    ///     .distribution_function(|upd| upd.from().map(|user| user.id))
173    ///     .build();
174    /// # let _: Dispatcher<_, (), _> = dp;
175    /// ```
176    ///
177    /// Not grouping updates at all, always processing updates concurrently:
178    ///
179    /// ```
180    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
181    ///
182    /// let bot = Bot::new("TOKEN");
183    /// let handler = dptree::entry() /* ... */;
184    /// let dp = Dispatcher::builder(bot, handler).distribution_function(|_| None::<()>).build();
185    /// # let _: Dispatcher<_, (), _> = dp;
186    /// ```
187    #[must_use]
188    pub fn distribution_function<K>(
189        self,
190        f: fn(&Update) -> Option<K>,
191    ) -> DispatcherBuilder<R, Err, K>
192    where
193        K: Hash + Eq,
194    {
195        let Self {
196            bot,
197            dependencies,
198            handler,
199            default_handler,
200            error_handler,
201            ctrlc_handler,
202            distribution_f: _,
203            worker_queue_size,
204            max_pending_updates,
205        } = self;
206
207        DispatcherBuilder {
208            bot,
209            dependencies,
210            handler,
211            default_handler,
212            error_handler,
213            ctrlc_handler,
214            distribution_f: f,
215            worker_queue_size,
216            max_pending_updates,
217        }
218    }
219
220    /// Constructs [`Dispatcher`].
221    ///
222    /// ## Panics
223    /// This function will panic at run-time if [`dptree`] fails to type-check
224    /// the provided handler, or if a queue limit is zero or exceeds Tokio's
225    /// semaphore limit.
226    #[must_use]
227    pub fn build(self) -> Dispatcher<R, Err, Key> {
228        let Self {
229            bot,
230            dependencies,
231            handler,
232            default_handler,
233            error_handler,
234            distribution_f,
235            worker_queue_size,
236            ctrlc_handler,
237            max_pending_updates,
238        } = self;
239
240        let max_pending_updates = max_pending_updates.unwrap_or(worker_queue_size);
241        assert!(
242            (1..=Semaphore::MAX_PERMITS).contains(&worker_queue_size),
243            "worker_queue_size must be in 1..=Semaphore::MAX_PERMITS"
244        );
245        assert!(
246            (1..=Semaphore::MAX_PERMITS).contains(&max_pending_updates),
247            "max_pending_updates must be in 1..=Semaphore::MAX_PERMITS"
248        );
249
250        dptree::type_check(
251            handler.sig(),
252            &dependencies,
253            &[
254                dptree::Type::of::<R>(),
255                dptree::Type::of::<teloxide_core::types::Update>(),
256                dptree::Type::of::<teloxide_core::types::BotFullInfo>(),
257            ],
258        );
259
260        // If the `ctrlc_handler` feature is not enabled, don't emit a warning.
261        let _ = ctrlc_handler;
262
263        let dp = Dispatcher {
264            bot,
265            dependencies,
266            handler,
267            default_handler,
268            error_handler,
269            state: ShutdownToken::new(),
270            distribution_f,
271            worker_queue_size,
272            max_pending_updates,
273        };
274
275        #[cfg(feature = "ctrlc_handler")]
276        {
277            if ctrlc_handler {
278                let mut dp = dp;
279                dp.setup_ctrlc_handler_inner();
280                return dp;
281            }
282        }
283
284        dp
285    }
286}
287
288/// The base for update dispatching.
289///
290/// ## Update grouping
291///
292/// `Dispatcher` generally processes updates concurrently. However, by default,
293/// updates from the same chat are processed sequentially. Learn more about
294/// [update grouping].
295///
296/// See also: ["Dispatching or
297/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
298///
299/// [update grouping]: DispatcherBuilder#update-grouping
300pub struct Dispatcher<R, Err, Key> {
301    bot: R,
302    dependencies: DependencyMap,
303
304    handler: Arc<UpdateHandler<Err>>,
305    default_handler: DefaultHandler,
306
307    distribution_f: fn(&Update) -> Option<Key>,
308    worker_queue_size: usize,
309    max_pending_updates: usize,
310
311    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
312
313    state: ShutdownToken,
314}
315
316struct Workers<Key> {
317    // Tokio TX channel parts associated with chat IDs that consume updates sequentially.
318    workers: HashMap<Key, Worker>,
319    // The default TX part that consume updates concurrently.
320    default_worker: Option<Worker>,
321}
322
323impl<Key> Default for Workers<Key> {
324    fn default() -> Self {
325        Self { workers: HashMap::new(), default_worker: None }
326    }
327}
328
329struct Worker {
330    tx: mpsc::Sender<PendingUpdate>,
331    handle: WorkerTask,
332    pending: Arc<AtomicUsize>,
333}
334
335struct PendingUpdate {
336    update: Update,
337    permit: OwnedSemaphorePermit,
338}
339
340struct WorkerTask(JoinHandle<()>);
341
342impl Drop for WorkerTask {
343    fn drop(&mut self) {
344        self.0.abort();
345    }
346}
347
348impl Future for WorkerTask {
349    type Output = Result<(), tokio::task::JoinError>;
350
351    fn poll(
352        mut self: std::pin::Pin<&mut Self>,
353        cx: &mut std::task::Context<'_>,
354    ) -> std::task::Poll<Self::Output> {
355        std::pin::Pin::new(&mut self.0).poll(cx)
356    }
357}
358
359// TODO: it is allowed to return message as response on telegram request in
360// webhooks, so we can allow this too. See more there: https://core.telegram.org/bots/api#making-requests-when-getting-updates
361
362/// A handler that processes updates from Telegram.
363pub type UpdateHandler<Err> = dptree::Handler<'static, Result<(), Err>, DpHandlerDescription>;
364
365type DefaultHandler = Arc<dyn Fn(Arc<Update>) -> BoxFuture<'static, ()> + Send + Sync>;
366
367impl<R, Err> Dispatcher<R, Err, DefaultKey>
368where
369    R: Requester + Clone + Send + Sync + 'static,
370    Err: Send + Sync + 'static,
371{
372    /// Constructs a new [`DispatcherBuilder`] with `bot` and `handler`.
373    #[must_use]
374    pub fn builder(bot: R, handler: UpdateHandler<Err>) -> DispatcherBuilder<R, Err, DefaultKey>
375    where
376        Err: Debug,
377    {
378        const DEFAULT_WORKER_QUEUE_SIZE: usize = 64;
379
380        DispatcherBuilder {
381            bot,
382            dependencies: DependencyMap::new(),
383            handler: Arc::new(handler),
384            default_handler: Arc::new(|upd| {
385                log::warn!("Unhandled update: {upd:?}");
386                Box::pin(async {})
387            }),
388            error_handler: LoggingErrorHandler::new(),
389            ctrlc_handler: false,
390            worker_queue_size: DEFAULT_WORKER_QUEUE_SIZE,
391            max_pending_updates: None,
392            distribution_f: default_distribution_function,
393        }
394    }
395}
396
397impl<R, Err, Key> Dispatcher<R, Err, Key>
398where
399    R: Requester + Clone + Send + Sync + 'static,
400    Err: Send + Sync + 'static,
401    Key: Hash + Eq + Clone + Send,
402{
403    /// Starts your bot with the default parameters.
404    ///
405    /// The default parameters are a long polling update listener and log all
406    /// errors produced by this listener.
407    ///
408    /// Each time a handler is invoked, [`Dispatcher`] adds the following
409    /// dependencies (in addition to those passed to
410    /// [`DispatcherBuilder::dependencies`]):
411    ///
412    ///  - Your bot passed to [`Dispatcher::builder`];
413    ///  - An update from Telegram;
414    ///  - [`crate::types::BotFullInfo`] (can be used in
415    ///    [`HandlerExt::filter_command`]).
416    ///
417    /// [`HandlerExt::filter_command`]: crate::dispatching::HandlerExt::filter_command
418    pub async fn dispatch(&mut self)
419    where
420        R: Requester + Clone,
421        <R as Requester>::GetUpdates: Send,
422    {
423        let listener = update_listeners::polling_default(self.bot.clone()).await;
424        let error_handler =
425            LoggingErrorHandler::with_custom_text("An error from the update listener");
426
427        self.dispatch_with_listener(listener, error_handler).await;
428    }
429
430    /// Starts your bot with custom `update_listener` and
431    /// `update_listener_error_handler`.
432    ///
433    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
434    /// The listener error handler receives those initial dependencies, but
435    /// there is no current update when receiving an update fails.
436    pub async fn dispatch_with_listener<'a, UListener, Eh>(
437        &'a mut self,
438        update_listener: UListener,
439        update_listener_error_handler: Arc<Eh>,
440    ) where
441        UListener: UpdateListener + Send + 'a,
442        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
443        UListener::Err: Debug,
444    {
445        self.try_dispatch_with_listener(update_listener, update_listener_error_handler)
446            .await
447            .expect("Couldn't prepare dispatching context")
448    }
449
450    /// Same as `dispatch_with_listener` but returns a `Err(_)` instead of
451    /// panicking when the initial telegram api call (`get_me`) fails.
452    ///
453    /// Starts your bot with custom `update_listener` and
454    /// `update_listener_error_handler`.
455    ///
456    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
457    pub async fn try_dispatch_with_listener<'a, UListener, Eh>(
458        &'a mut self,
459        mut update_listener: UListener,
460        update_listener_error_handler: Arc<Eh>,
461    ) -> Result<(), R::Err>
462    where
463        UListener: UpdateListener + Send + 'a,
464        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
465        UListener::Err: Debug,
466    {
467        // FIXME: there should be a way to check if dependency is already inserted
468        let me = self.bot.get_me().send().await?;
469        self.dependencies.insert(me);
470        self.dependencies.insert(self.bot.clone());
471
472        let description = self.handler.description();
473        let allowed_updates = description.allowed_updates();
474        log::debug!("hinting allowed updates: {allowed_updates:?}");
475        update_listener.hint_allowed_updates(&mut allowed_updates.into_iter());
476
477        self.start_listening(update_listener, update_listener_error_handler).await;
478
479        Ok(())
480    }
481
482    async fn start_listening<'a, UListener, Eh>(
483        &'a mut self,
484        mut update_listener: UListener,
485        update_listener_error_handler: Arc<Eh>,
486    ) where
487        UListener: UpdateListener + 'a,
488        Eh: ErrorHandler<UListener::Err> + 'a,
489        UListener::Err: Debug,
490    {
491        let _run = self.state.start_dispatching(update_listener.stop_token());
492        let mut workers = Workers::default();
493        let capacity = Arc::new(Semaphore::new(self.max_pending_updates));
494
495        let stream = update_listener.as_stream();
496        tokio::pin!(stream);
497
498        loop {
499            let permit = Arc::clone(&capacity).acquire_owned().await.expect("semaphore not closed");
500            if workers.workers.len() >= self.max_pending_updates {
501                // A zero count means that the worker has processed every
502                // update sent to it, so it can be discarded without reordering.
503                workers.workers.retain(|_, worker| worker.pending.load(Ordering::Acquire) != 0);
504            }
505
506            let Some(update) = stream.next().await else { break };
507            self.process_update(update, &update_listener_error_handler, &mut workers, permit).await;
508        }
509
510        workers
511            .workers
512            .drain()
513            .map(|(_chat_id, worker)| worker.handle)
514            .chain(workers.default_worker.take().map(|worker| worker.handle))
515            .collect::<FuturesUnordered<_>>()
516            .for_each(|res| async {
517                res.expect("Failed to wait for a worker.");
518            })
519            .await;
520    }
521
522    async fn process_update<LErr, LErrHandler>(
523        &self,
524        update: Result<Update, LErr>,
525        err_handler: &Arc<LErrHandler>,
526        workers: &mut Workers<Key>,
527        permit: OwnedSemaphorePermit,
528    ) where
529        LErrHandler: ErrorHandler<LErr>,
530    {
531        match update {
532            Ok(upd) => {
533                if let UpdateKind::Error(err) = upd.kind {
534                    log::error!(
535                        "Cannot parse an update.\nError: {err:?}\n\
536                            This is a bug in teloxide-core, please open an issue here: \
537                            https://github.com/teloxide/teloxide/issues.",
538                    );
539                    return;
540                }
541
542                let worker = match (self.distribution_f)(&upd) {
543                    Some(key) => workers.workers.entry(key).or_insert_with(|| {
544                        let deps = self.dependencies.clone();
545                        let handler = Arc::clone(&self.handler);
546                        let default_handler = Arc::clone(&self.default_handler);
547                        let error_handler = Arc::clone(&self.error_handler);
548
549                        spawn_worker(
550                            deps,
551                            handler,
552                            default_handler,
553                            error_handler,
554                            self.worker_queue_size,
555                        )
556                    }),
557                    None => workers.default_worker.get_or_insert_with(|| {
558                        let deps = self.dependencies.clone();
559                        let handler = Arc::clone(&self.handler);
560                        let default_handler = Arc::clone(&self.default_handler);
561                        let error_handler = Arc::clone(&self.error_handler);
562
563                        spawn_default_worker(
564                            deps,
565                            handler,
566                            default_handler,
567                            error_handler,
568                            self.worker_queue_size,
569                            self.max_pending_updates,
570                        )
571                    }),
572                };
573
574                worker.pending.fetch_add(1, Ordering::Relaxed);
575                worker.tx.send(PendingUpdate { update: upd, permit }).await.expect("TX is dead");
576            }
577            Err(err) => err_handler.clone().handle_error(err, self.dependencies.clone()).await,
578        }
579    }
580
581    /// Returns a shutdown token, which can later be used to
582    /// [`ShutdownToken::shutdown`].
583    pub fn shutdown_token(&self) -> ShutdownToken {
584        self.state.clone()
585    }
586}
587
588impl<R, Err, Key> Dispatcher<R, Err, Key> {
589    #[cfg(feature = "ctrlc_handler")]
590    fn setup_ctrlc_handler_inner(&mut self) {
591        let token = self.state.clone();
592        tokio::spawn(async move {
593            loop {
594                tokio::signal::ctrl_c().await.expect("Failed to listen for ^C");
595
596                match token.shutdown() {
597                    Ok(f) => {
598                        log::info!("^C received, trying to shutdown the dispatcher...");
599                        f.await;
600                        log::info!("dispatcher is shutdown...");
601                    }
602                    Err(_) => {
603                        log::info!("^C received, the dispatcher isn't running, ignoring the signal")
604                    }
605                }
606            }
607        });
608    }
609}
610
611fn spawn_worker<Err>(
612    deps: DependencyMap,
613    handler: Arc<UpdateHandler<Err>>,
614    default_handler: DefaultHandler,
615    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
616    queue_size: usize,
617) -> Worker
618where
619    Err: Send + Sync + 'static,
620{
621    let (tx, mut rx) = mpsc::channel::<PendingUpdate>(queue_size);
622    let pending = Arc::new(AtomicUsize::new(0));
623    let worker_pending = Arc::clone(&pending);
624
625    let deps = Arc::new(deps);
626
627    let handle = tokio::spawn(async move {
628        while let Some(PendingUpdate { update, permit }) = rx.recv().await {
629            let deps = Arc::clone(&deps);
630            let handler = Arc::clone(&handler);
631            let default_handler = Arc::clone(&default_handler);
632            let error_handler = Arc::clone(&error_handler);
633
634            handle_update(update, deps, handler, default_handler, error_handler).await;
635
636            worker_pending.fetch_sub(1, Ordering::Release);
637            drop(permit);
638        }
639    });
640
641    Worker { tx, handle: WorkerTask(handle), pending }
642}
643
644fn spawn_default_worker<Err>(
645    deps: DependencyMap,
646    handler: Arc<UpdateHandler<Err>>,
647    default_handler: DefaultHandler,
648    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
649    queue_size: usize,
650    max_pending_updates: usize,
651) -> Worker
652where
653    Err: Send + Sync + 'static,
654{
655    let (tx, rx) = mpsc::channel::<PendingUpdate>(queue_size);
656    let pending = Arc::new(AtomicUsize::new(0));
657    let worker_pending = Arc::clone(&pending);
658
659    let deps = Arc::new(deps);
660
661    let handle = tokio::spawn(ReceiverStream::new(rx).for_each_concurrent(
662        max_pending_updates,
663        move |PendingUpdate { update, permit }| {
664            let deps = Arc::clone(&deps);
665            let handler = Arc::clone(&handler);
666            let default_handler = Arc::clone(&default_handler);
667            let error_handler = Arc::clone(&error_handler);
668            let worker_pending = Arc::clone(&worker_pending);
669
670            async move {
671                handle_update(update, deps, handler, default_handler, error_handler).await;
672                worker_pending.fetch_sub(1, Ordering::Release);
673                drop(permit);
674            }
675        },
676    ));
677
678    Worker { tx, handle: WorkerTask(handle), pending }
679}
680
681async fn handle_update<Err>(
682    update: Update,
683    deps: Arc<DependencyMap>,
684    handler: Arc<UpdateHandler<Err>>,
685    default_handler: DefaultHandler,
686    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
687) where
688    Err: Send + Sync + 'static,
689{
690    let id = update.id;
691    let result = AssertUnwindSafe(async move {
692        let mut deps = deps.deref().clone();
693        deps.insert(update);
694
695        match handler.dispatch(deps.clone()).await {
696            ControlFlow::Break(Ok(())) => {}
697            ControlFlow::Break(Err(err)) => error_handler.handle_error(err, deps).await,
698            ControlFlow::Continue(deps) => {
699                let update = deps.get();
700                (default_handler)(update).await;
701            }
702        }
703    })
704    .catch_unwind()
705    .await;
706
707    if let Err(panic) = result {
708        let message = panic
709            .downcast_ref::<&str>()
710            .copied()
711            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
712            .unwrap_or("non-string panic payload");
713        log::error!("Update handler panicked for update {id:?}: {message}");
714    }
715}
716#[cfg(test)]
717mod tests {
718    use std::{convert::Infallible, pin::pin};
719
720    use futures::{future, stream};
721    use teloxide_core::Bot;
722
723    use super::*;
724    use crate::{
725        stop::{mk_stop_token, StopFlag, StopToken},
726        update_listeners::StatefulListener,
727    };
728
729    fn update(id: u32) -> Update {
730        let update: Update = serde_json::from_value(serde_json::json!({
731            "update_id": id,
732            "message": {"message_id": 1, "date": 0, "chat": {"id": 1, "type": "private"}}
733        }))
734        .unwrap();
735        assert!(matches!(update.kind, UpdateKind::Message(_)), "{update:?}");
736        update
737    }
738
739    fn listener(
740        updates: impl futures::Stream<Item = Result<Update, Infallible>> + Send + 'static,
741    ) -> (impl UpdateListener<Err = Infallible> + Send, StopFlag) {
742        let (token, flag) = mk_stop_token();
743        let stop = flag.clone();
744        let listener = StatefulListener::new(
745            (Some(updates.take_until(stop)), token),
746            |state: &mut (Option<_>, StopToken)| state.0.take().unwrap(),
747            |state: &mut (Option<_>, StopToken)| state.1.clone(),
748        );
749        (listener, flag)
750    }
751
752    #[tokio::test]
753    async fn cancelling_dispatch_aborts_workers_and_allows_another_run() {
754        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
755        let handler = dptree::endpoint(move || {
756            let tx = started_tx.clone();
757            async move {
758                // Dropped when the in-flight handler is aborted.
759                let (alive_tx, alive_rx) = tokio::sync::oneshot::channel::<()>();
760                tx.send(alive_rx).unwrap();
761                let _alive = alive_tx;
762                future::pending::<Result<(), Infallible>>().await
763            }
764        });
765        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler).build();
766        let shutdown = dispatcher.shutdown_token();
767        for draining in [false, true] {
768            let updates = stream::iter([Ok(update(1))]).chain(stream::poll_fn(move |_| {
769                if draining {
770                    std::task::Poll::Ready(None)
771                } else {
772                    std::task::Poll::Pending
773                }
774            }));
775            let (listener, flag) = listener(updates);
776
777            let completion;
778            let alive;
779            {
780                let mut run =
781                    pin!(dispatcher.start_listening(listener, LoggingErrorHandler::new()));
782                alive = tokio::select! {
783                    alive = started_rx.recv() => alive.unwrap(),
784                    () = &mut run => panic!("dispatcher returned before its worker finished"),
785                };
786                // Test cancellation both while receiving and while draining workers.
787                completion = draining.then(|| shutdown.shutdown().unwrap());
788            }
789            assert!(flag.is_stopped());
790            assert!(shutdown.shutdown().is_err());
791            if let Some(completion) = completion {
792                completion.await;
793            }
794            assert!(alive.await.is_err());
795        }
796
797        let (listener, _) = self::listener(stream::empty());
798        dispatcher.start_listening(listener, LoggingErrorHandler::new()).await;
799    }
800
801    #[tokio::test]
802    async fn blocked_keyless_handler_backpressures_the_listener() {
803        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
804        let release = release_rx.map(|result| result.unwrap()).shared();
805        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
806        let handler = dptree::endpoint(move |update: Update| {
807            let started_tx = started_tx.clone();
808            let release = release.clone();
809            async move {
810                started_tx.send(update.id.0).unwrap();
811                release.await;
812                Ok::<_, Infallible>(())
813            }
814        });
815        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler)
816            .distribution_function(|_| None::<()>)
817            .worker_queue_size(1)
818            .build();
819
820        let reads = Arc::new(AtomicUsize::new(0));
821        let (listener, _) = listener(stream::iter((1..=8).map({
822            let reads = Arc::clone(&reads);
823            move |id| {
824                reads.fetch_add(1, Ordering::Relaxed);
825                Ok(update(id))
826            }
827        })));
828        let mut run = pin!(dispatcher.start_listening(listener, LoggingErrorHandler::new()));
829        tokio::select! {
830            id = started_rx.recv() => assert_eq!(id, Some(1)),
831            () = &mut run => panic!("dispatcher returned while a handler was blocked"),
832        }
833        assert!(futures::poll!(&mut run).is_pending());
834        assert_eq!(reads.load(Ordering::Relaxed), 1);
835        release_tx.send(()).unwrap();
836        run.await;
837        assert_eq!(reads.load(Ordering::Relaxed), 8);
838    }
839
840    #[tokio::test]
841    async fn worker_continues_after_handler_panic() {
842        let (handled_tx, mut handled_rx) = mpsc::unbounded_channel();
843        let handler = dptree::endpoint(move |update: Update| {
844            let handled_tx = handled_tx.clone();
845            async move {
846                assert_ne!(update.id.0, 1, "broken handler");
847                handled_tx.send(update.id.0).unwrap();
848                Ok::<_, Infallible>(())
849            }
850        });
851        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler).build();
852        let (listener, _) = listener(stream::iter([Ok(update(1)), Ok(update(2))]));
853        dispatcher.start_listening(listener, LoggingErrorHandler::new()).await;
854        assert_eq!(handled_rx.try_recv(), Ok(2));
855    }
856
857    #[tokio::test]
858    async fn handler_error_receives_initial_dependencies() {
859        let initial = dptree::deps!["configured"];
860        let handler = dptree::map(|| 42_u32).endpoint(|| async { Err("handler failed") });
861        let update = Update {
862            id: crate::types::UpdateId(1),
863            kind: UpdateKind::Error(serde_json::Value::Null),
864        };
865        let (tx, rx) = tokio::sync::oneshot::channel();
866        let tx = std::sync::Mutex::new(Some(tx));
867        let error_handler = move |err, deps: DependencyMap| {
868            let tx = tx.lock().unwrap().take().unwrap();
869            async move { tx.send((err, deps)).unwrap() }
870        };
871
872        handle_update(
873            update,
874            Arc::new(initial),
875            Arc::new(handler),
876            Arc::new(|_| unreachable!()),
877            Arc::new(error_handler),
878        )
879        .await;
880
881        let (err, deps) = rx.await.unwrap();
882        assert_eq!(err, "handler failed");
883        assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
884        assert_eq!(deps.try_get::<Update>().unwrap().id, crate::types::UpdateId(1));
885        assert!(deps.try_get::<u32>().is_none());
886    }
887
888    #[tokio::test]
889    async fn listener_error_receives_initial_dependencies_without_current_update() {
890        let dispatcher = Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
891            .dependencies(dptree::deps!["configured"])
892            .build();
893        let error_handler = Arc::new(|err, deps: DependencyMap| async move {
894            assert_eq!(err, "listener failed");
895            assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
896            assert!(deps.try_get::<Update>().is_none());
897        });
898        let mut workers = Workers::default();
899        let permit = Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap();
900        dispatcher
901            .process_update(Err("listener failed"), &error_handler, &mut workers, permit)
902            .await;
903    }
904
905    #[tokio::test]
906    async fn test_tokio_spawn() {
907        tokio::spawn(async {
908            // Just check that this code compiles.
909            if false {
910                Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
911                    .build()
912                    .dispatch()
913                    .await;
914            }
915        })
916        .await
917        .unwrap();
918    }
919}