teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
use crate::{
    dispatching::{
        distribution::default_distribution_function, DefaultKey, DpHandlerDescription,
        ShutdownToken,
    },
    error_handlers::{ErrorHandler, LoggingErrorHandler},
    requests::{Request, Requester},
    types::{Update, UpdateKind},
    update_listeners::{self, UpdateListener},
};

use dptree::di::DependencyMap;
use futures::{future::BoxFuture, stream::FuturesUnordered, FutureExt as _, StreamExt as _};
use tokio::{
    sync::{mpsc, OwnedSemaphorePermit, Semaphore},
    task::JoinHandle,
};
use tokio_stream::wrappers::ReceiverStream;

use std::{
    collections::HashMap,
    fmt::Debug,
    future::Future,
    hash::Hash,
    ops::{ControlFlow, Deref},
    panic::AssertUnwindSafe,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
};

/// The builder for [`Dispatcher`].
///
/// See also: ["Dispatching or
/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
pub struct DispatcherBuilder<R, Err, Key> {
    bot: R,
    dependencies: DependencyMap,
    handler: Arc<UpdateHandler<Err>>,
    default_handler: DefaultHandler,
    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
    ctrlc_handler: bool,
    distribution_f: fn(&Update) -> Option<Key>,
    worker_queue_size: usize,
    max_pending_updates: Option<usize>,
}

impl<R, Err, Key> DispatcherBuilder<R, Err, Key>
where
    R: Clone + Requester + Clone + Send + Sync + 'static,
    Err: Debug + Send + Sync + 'static,
{
    /// Specifies a handler that will be called for an unhandled update.
    ///
    /// By default, it is a mere [`log::warn`].
    #[must_use]
    pub fn default_handler<H, Fut>(self, handler: H) -> Self
    where
        H: Fn(Arc<Update>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let handler = Arc::new(handler);

        Self {
            default_handler: Arc::new(move |upd| {
                let handler = Arc::clone(&handler);
                Box::pin(handler(upd))
            }),
            ..self
        }
    }

    /// Specifies a handler that will be called on a handler error.
    ///
    /// Its dependency map contains the dependencies available before
    /// dispatching the update, including the bot, [`crate::types::Me`] and
    /// the current [`Update`]. Values added by the handler tree are not
    /// included.
    ///
    /// By default, it is [`LoggingErrorHandler`].
    #[must_use]
    pub fn error_handler(self, handler: Arc<dyn ErrorHandler<Err> + Send + Sync>) -> Self {
        Self { error_handler: handler, ..self }
    }

    /// Specifies dependencies that can be used inside of handlers.
    ///
    /// By default, there is no dependencies.
    #[must_use]
    pub fn dependencies(self, dependencies: DependencyMap) -> Self {
        Self { dependencies, ..self }
    }

    /// Enables the `^C` handler that [`shutdown`]s dispatching.
    ///
    /// [`shutdown`]: ShutdownToken::shutdown
    #[cfg(feature = "ctrlc_handler")]
    #[must_use]
    pub fn enable_ctrlc_handler(self) -> Self {
        Self { ctrlc_handler: true, ..self }
    }

    /// Specifies size of the queue for workers.
    ///
    /// By default it's 64.
    #[must_use]
    pub fn worker_queue_size(self, size: usize) -> Self {
        Self { worker_queue_size: size, ..self }
    }

    /// Sets the global maximum number of queued and running updates, across
    /// both keyed and unkeyed workers. Defaults to the worker queue size.
    ///
    /// When all slots are occupied, the dispatcher stops reading updates from
    /// its listener until a slot becomes available. This includes reading
    /// buffered updates during graceful shutdown.
    #[must_use]
    pub fn max_pending_updates(self, limit: usize) -> Self {
        Self { max_pending_updates: Some(limit), ..self }
    }

    /// Specifies the stack size available to the dispatcher.
    ///
    /// By default, it's 8 * 1024 * 1024 bytes (8 MiB).
    #[must_use]
    #[deprecated(since = "0.15.0", note = "This method is a no-op; you can just remove it.")]
    pub fn stack_size(self, _size: usize) -> Self {
        self
    }

    /// Specifies the distribution function that decides how updates are grouped
    /// before execution.
    ///
    /// ## Update grouping
    ///
    /// When [`Dispatcher`] receives updates, it runs dispatching tree
    /// (handlers) concurrently. This means that multiple updates can be
    /// processed at the same time.
    ///
    /// However, this is not always convenient. For example, if you have global
    /// state, then you may want to process some updates sequentially, to
    /// prevent state inconsistencies.
    ///
    /// This is why `teloxide` allows grouping updates. Updates for which the
    /// distribution function `f` returns the same "distribution key" `K` will
    /// be run in sequence (while still being processed concurrently with the
    /// updates with different distribution keys).
    ///
    /// Updates for which `f` returns `None` can run concurrently, subject to
    /// [`Self::max_pending_updates`].
    ///
    /// ## Default distribution function
    ///
    /// By default the distribution function is equivalent to `|upd|
    /// upd.chat().map(|chat| chat.id)`, so updates from the same chat will be
    /// processed sequentially.
    ///
    /// This pair nicely with dialogue system, which has state attached to
    /// chats.
    ///
    /// ## Examples
    ///
    /// Grouping updates by user who caused this update to happen:
    ///
    /// ```
    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
    ///
    /// let bot = Bot::new("TOKEN");
    /// let handler = dptree::entry() /* ... */;
    /// let dp = Dispatcher::builder(bot, handler)
    ///     .distribution_function(|upd| upd.from().map(|user| user.id))
    ///     .build();
    /// # let _: Dispatcher<_, (), _> = dp;
    /// ```
    ///
    /// Not grouping updates at all, always processing updates concurrently:
    ///
    /// ```
    /// use teloxide::{dispatching::Dispatcher, dptree, Bot};
    ///
    /// let bot = Bot::new("TOKEN");
    /// let handler = dptree::entry() /* ... */;
    /// let dp = Dispatcher::builder(bot, handler).distribution_function(|_| None::<()>).build();
    /// # let _: Dispatcher<_, (), _> = dp;
    /// ```
    #[must_use]
    pub fn distribution_function<K>(
        self,
        f: fn(&Update) -> Option<K>,
    ) -> DispatcherBuilder<R, Err, K>
    where
        K: Hash + Eq,
    {
        let Self {
            bot,
            dependencies,
            handler,
            default_handler,
            error_handler,
            ctrlc_handler,
            distribution_f: _,
            worker_queue_size,
            max_pending_updates,
        } = self;

        DispatcherBuilder {
            bot,
            dependencies,
            handler,
            default_handler,
            error_handler,
            ctrlc_handler,
            distribution_f: f,
            worker_queue_size,
            max_pending_updates,
        }
    }

    /// Constructs [`Dispatcher`].
    ///
    /// ## Panics
    /// This function will panic at run-time if [`dptree`] fails to type-check
    /// the provided handler, or if a queue limit is zero or exceeds Tokio's
    /// semaphore limit.
    #[must_use]
    pub fn build(self) -> Dispatcher<R, Err, Key> {
        let Self {
            bot,
            dependencies,
            handler,
            default_handler,
            error_handler,
            distribution_f,
            worker_queue_size,
            ctrlc_handler,
            max_pending_updates,
        } = self;

        let max_pending_updates = max_pending_updates.unwrap_or(worker_queue_size);
        assert!(
            (1..=Semaphore::MAX_PERMITS).contains(&worker_queue_size),
            "worker_queue_size must be in 1..=Semaphore::MAX_PERMITS"
        );
        assert!(
            (1..=Semaphore::MAX_PERMITS).contains(&max_pending_updates),
            "max_pending_updates must be in 1..=Semaphore::MAX_PERMITS"
        );

        dptree::type_check(
            handler.sig(),
            &dependencies,
            &[
                dptree::Type::of::<R>(),
                dptree::Type::of::<teloxide_core::types::Update>(),
                dptree::Type::of::<teloxide_core::types::BotFullInfo>(),
            ],
        );

        // If the `ctrlc_handler` feature is not enabled, don't emit a warning.
        let _ = ctrlc_handler;

        let dp = Dispatcher {
            bot,
            dependencies,
            handler,
            default_handler,
            error_handler,
            state: ShutdownToken::new(),
            distribution_f,
            worker_queue_size,
            max_pending_updates,
        };

        #[cfg(feature = "ctrlc_handler")]
        {
            if ctrlc_handler {
                let mut dp = dp;
                dp.setup_ctrlc_handler_inner();
                return dp;
            }
        }

        dp
    }
}

/// The base for update dispatching.
///
/// ## Update grouping
///
/// `Dispatcher` generally processes updates concurrently. However, by default,
/// updates from the same chat are processed sequentially. Learn more about
/// [update grouping].
///
/// See also: ["Dispatching or
/// REPLs?"](../dispatching/index.html#dispatching-or-repls)
///
/// [update grouping]: DispatcherBuilder#update-grouping
pub struct Dispatcher<R, Err, Key> {
    bot: R,
    dependencies: DependencyMap,

    handler: Arc<UpdateHandler<Err>>,
    default_handler: DefaultHandler,

    distribution_f: fn(&Update) -> Option<Key>,
    worker_queue_size: usize,
    max_pending_updates: usize,

    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,

    state: ShutdownToken,
}

struct Workers<Key> {
    // Tokio TX channel parts associated with chat IDs that consume updates sequentially.
    workers: HashMap<Key, Worker>,
    // The default TX part that consume updates concurrently.
    default_worker: Option<Worker>,
}

impl<Key> Default for Workers<Key> {
    fn default() -> Self {
        Self { workers: HashMap::new(), default_worker: None }
    }
}

struct Worker {
    tx: mpsc::Sender<PendingUpdate>,
    handle: WorkerTask,
    pending: Arc<AtomicUsize>,
}

struct PendingUpdate {
    update: Update,
    permit: OwnedSemaphorePermit,
}

struct WorkerTask(JoinHandle<()>);

impl Drop for WorkerTask {
    fn drop(&mut self) {
        self.0.abort();
    }
}

impl Future for WorkerTask {
    type Output = Result<(), tokio::task::JoinError>;

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        std::pin::Pin::new(&mut self.0).poll(cx)
    }
}

// TODO: it is allowed to return message as response on telegram request in
// webhooks, so we can allow this too. See more there: https://core.telegram.org/bots/api#making-requests-when-getting-updates

/// A handler that processes updates from Telegram.
pub type UpdateHandler<Err> = dptree::Handler<'static, Result<(), Err>, DpHandlerDescription>;

type DefaultHandler = Arc<dyn Fn(Arc<Update>) -> BoxFuture<'static, ()> + Send + Sync>;

impl<R, Err> Dispatcher<R, Err, DefaultKey>
where
    R: Requester + Clone + Send + Sync + 'static,
    Err: Send + Sync + 'static,
{
    /// Constructs a new [`DispatcherBuilder`] with `bot` and `handler`.
    #[must_use]
    pub fn builder(bot: R, handler: UpdateHandler<Err>) -> DispatcherBuilder<R, Err, DefaultKey>
    where
        Err: Debug,
    {
        const DEFAULT_WORKER_QUEUE_SIZE: usize = 64;

        DispatcherBuilder {
            bot,
            dependencies: DependencyMap::new(),
            handler: Arc::new(handler),
            default_handler: Arc::new(|upd| {
                log::warn!("Unhandled update: {upd:?}");
                Box::pin(async {})
            }),
            error_handler: LoggingErrorHandler::new(),
            ctrlc_handler: false,
            worker_queue_size: DEFAULT_WORKER_QUEUE_SIZE,
            max_pending_updates: None,
            distribution_f: default_distribution_function,
        }
    }
}

impl<R, Err, Key> Dispatcher<R, Err, Key>
where
    R: Requester + Clone + Send + Sync + 'static,
    Err: Send + Sync + 'static,
    Key: Hash + Eq + Clone + Send,
{
    /// Starts your bot with the default parameters.
    ///
    /// The default parameters are a long polling update listener and log all
    /// errors produced by this listener.
    ///
    /// Each time a handler is invoked, [`Dispatcher`] adds the following
    /// dependencies (in addition to those passed to
    /// [`DispatcherBuilder::dependencies`]):
    ///
    ///  - Your bot passed to [`Dispatcher::builder`];
    ///  - An update from Telegram;
    ///  - [`crate::types::BotFullInfo`] (can be used in
    ///    [`HandlerExt::filter_command`]).
    ///
    /// [`HandlerExt::filter_command`]: crate::dispatching::HandlerExt::filter_command
    pub async fn dispatch(&mut self)
    where
        R: Requester + Clone,
        <R as Requester>::GetUpdates: Send,
    {
        let listener = update_listeners::polling_default(self.bot.clone()).await;
        let error_handler =
            LoggingErrorHandler::with_custom_text("An error from the update listener");

        self.dispatch_with_listener(listener, error_handler).await;
    }

    /// Starts your bot with custom `update_listener` and
    /// `update_listener_error_handler`.
    ///
    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
    /// The listener error handler receives those initial dependencies, but
    /// there is no current update when receiving an update fails.
    pub async fn dispatch_with_listener<'a, UListener, Eh>(
        &'a mut self,
        update_listener: UListener,
        update_listener_error_handler: Arc<Eh>,
    ) where
        UListener: UpdateListener + Send + 'a,
        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
        UListener::Err: Debug,
    {
        self.try_dispatch_with_listener(update_listener, update_listener_error_handler)
            .await
            .expect("Couldn't prepare dispatching context")
    }

    /// Same as `dispatch_with_listener` but returns a `Err(_)` instead of
    /// panicking when the initial telegram api call (`get_me`) fails.
    ///
    /// Starts your bot with custom `update_listener` and
    /// `update_listener_error_handler`.
    ///
    /// This method adds the same dependencies as [`Dispatcher::dispatch`].
    pub async fn try_dispatch_with_listener<'a, UListener, Eh>(
        &'a mut self,
        mut update_listener: UListener,
        update_listener_error_handler: Arc<Eh>,
    ) -> Result<(), R::Err>
    where
        UListener: UpdateListener + Send + 'a,
        Eh: ErrorHandler<UListener::Err> + Send + Sync + 'a,
        UListener::Err: Debug,
    {
        // FIXME: there should be a way to check if dependency is already inserted
        let me = self.bot.get_me().send().await?;
        self.dependencies.insert(me);
        self.dependencies.insert(self.bot.clone());

        let description = self.handler.description();
        let allowed_updates = description.allowed_updates();
        log::debug!("hinting allowed updates: {allowed_updates:?}");
        update_listener.hint_allowed_updates(&mut allowed_updates.into_iter());

        self.start_listening(update_listener, update_listener_error_handler).await;

        Ok(())
    }

    async fn start_listening<'a, UListener, Eh>(
        &'a mut self,
        mut update_listener: UListener,
        update_listener_error_handler: Arc<Eh>,
    ) where
        UListener: UpdateListener + 'a,
        Eh: ErrorHandler<UListener::Err> + 'a,
        UListener::Err: Debug,
    {
        let _run = self.state.start_dispatching(update_listener.stop_token());
        let mut workers = Workers::default();
        let capacity = Arc::new(Semaphore::new(self.max_pending_updates));

        let stream = update_listener.as_stream();
        tokio::pin!(stream);

        loop {
            let permit = Arc::clone(&capacity).acquire_owned().await.expect("semaphore not closed");
            if workers.workers.len() >= self.max_pending_updates {
                // A zero count means that the worker has processed every
                // update sent to it, so it can be discarded without reordering.
                workers.workers.retain(|_, worker| worker.pending.load(Ordering::Acquire) != 0);
            }

            let Some(update) = stream.next().await else { break };
            self.process_update(update, &update_listener_error_handler, &mut workers, permit).await;
        }

        workers
            .workers
            .drain()
            .map(|(_chat_id, worker)| worker.handle)
            .chain(workers.default_worker.take().map(|worker| worker.handle))
            .collect::<FuturesUnordered<_>>()
            .for_each(|res| async {
                res.expect("Failed to wait for a worker.");
            })
            .await;
    }

    async fn process_update<LErr, LErrHandler>(
        &self,
        update: Result<Update, LErr>,
        err_handler: &Arc<LErrHandler>,
        workers: &mut Workers<Key>,
        permit: OwnedSemaphorePermit,
    ) where
        LErrHandler: ErrorHandler<LErr>,
    {
        match update {
            Ok(upd) => {
                if let UpdateKind::Error(err) = upd.kind {
                    log::error!(
                        "Cannot parse an update.\nError: {err:?}\n\
                            This is a bug in teloxide-core, please open an issue here: \
                            https://github.com/teloxide/teloxide/issues.",
                    );
                    return;
                }

                let worker = match (self.distribution_f)(&upd) {
                    Some(key) => workers.workers.entry(key).or_insert_with(|| {
                        let deps = self.dependencies.clone();
                        let handler = Arc::clone(&self.handler);
                        let default_handler = Arc::clone(&self.default_handler);
                        let error_handler = Arc::clone(&self.error_handler);

                        spawn_worker(
                            deps,
                            handler,
                            default_handler,
                            error_handler,
                            self.worker_queue_size,
                        )
                    }),
                    None => workers.default_worker.get_or_insert_with(|| {
                        let deps = self.dependencies.clone();
                        let handler = Arc::clone(&self.handler);
                        let default_handler = Arc::clone(&self.default_handler);
                        let error_handler = Arc::clone(&self.error_handler);

                        spawn_default_worker(
                            deps,
                            handler,
                            default_handler,
                            error_handler,
                            self.worker_queue_size,
                            self.max_pending_updates,
                        )
                    }),
                };

                worker.pending.fetch_add(1, Ordering::Relaxed);
                worker.tx.send(PendingUpdate { update: upd, permit }).await.expect("TX is dead");
            }
            Err(err) => err_handler.clone().handle_error(err, self.dependencies.clone()).await,
        }
    }

    /// Returns a shutdown token, which can later be used to
    /// [`ShutdownToken::shutdown`].
    pub fn shutdown_token(&self) -> ShutdownToken {
        self.state.clone()
    }
}

impl<R, Err, Key> Dispatcher<R, Err, Key> {
    #[cfg(feature = "ctrlc_handler")]
    fn setup_ctrlc_handler_inner(&mut self) {
        let token = self.state.clone();
        tokio::spawn(async move {
            loop {
                tokio::signal::ctrl_c().await.expect("Failed to listen for ^C");

                match token.shutdown() {
                    Ok(f) => {
                        log::info!("^C received, trying to shutdown the dispatcher...");
                        f.await;
                        log::info!("dispatcher is shutdown...");
                    }
                    Err(_) => {
                        log::info!("^C received, the dispatcher isn't running, ignoring the signal")
                    }
                }
            }
        });
    }
}

fn spawn_worker<Err>(
    deps: DependencyMap,
    handler: Arc<UpdateHandler<Err>>,
    default_handler: DefaultHandler,
    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
    queue_size: usize,
) -> Worker
where
    Err: Send + Sync + 'static,
{
    let (tx, mut rx) = mpsc::channel::<PendingUpdate>(queue_size);
    let pending = Arc::new(AtomicUsize::new(0));
    let worker_pending = Arc::clone(&pending);

    let deps = Arc::new(deps);

    let handle = tokio::spawn(async move {
        while let Some(PendingUpdate { update, permit }) = rx.recv().await {
            let deps = Arc::clone(&deps);
            let handler = Arc::clone(&handler);
            let default_handler = Arc::clone(&default_handler);
            let error_handler = Arc::clone(&error_handler);

            handle_update(update, deps, handler, default_handler, error_handler).await;

            worker_pending.fetch_sub(1, Ordering::Release);
            drop(permit);
        }
    });

    Worker { tx, handle: WorkerTask(handle), pending }
}

fn spawn_default_worker<Err>(
    deps: DependencyMap,
    handler: Arc<UpdateHandler<Err>>,
    default_handler: DefaultHandler,
    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
    queue_size: usize,
    max_pending_updates: usize,
) -> Worker
where
    Err: Send + Sync + 'static,
{
    let (tx, rx) = mpsc::channel::<PendingUpdate>(queue_size);
    let pending = Arc::new(AtomicUsize::new(0));
    let worker_pending = Arc::clone(&pending);

    let deps = Arc::new(deps);

    let handle = tokio::spawn(ReceiverStream::new(rx).for_each_concurrent(
        max_pending_updates,
        move |PendingUpdate { update, permit }| {
            let deps = Arc::clone(&deps);
            let handler = Arc::clone(&handler);
            let default_handler = Arc::clone(&default_handler);
            let error_handler = Arc::clone(&error_handler);
            let worker_pending = Arc::clone(&worker_pending);

            async move {
                handle_update(update, deps, handler, default_handler, error_handler).await;
                worker_pending.fetch_sub(1, Ordering::Release);
                drop(permit);
            }
        },
    ));

    Worker { tx, handle: WorkerTask(handle), pending }
}

async fn handle_update<Err>(
    update: Update,
    deps: Arc<DependencyMap>,
    handler: Arc<UpdateHandler<Err>>,
    default_handler: DefaultHandler,
    error_handler: Arc<dyn ErrorHandler<Err> + Send + Sync>,
) where
    Err: Send + Sync + 'static,
{
    let id = update.id;
    let result = AssertUnwindSafe(async move {
        let mut deps = deps.deref().clone();
        deps.insert(update);

        match handler.dispatch(deps.clone()).await {
            ControlFlow::Break(Ok(())) => {}
            ControlFlow::Break(Err(err)) => error_handler.handle_error(err, deps).await,
            ControlFlow::Continue(deps) => {
                let update = deps.get();
                (default_handler)(update).await;
            }
        }
    })
    .catch_unwind()
    .await;

    if let Err(panic) = result {
        let message = panic
            .downcast_ref::<&str>()
            .copied()
            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
            .unwrap_or("non-string panic payload");
        log::error!("Update handler panicked for update {id:?}: {message}");
    }
}
#[cfg(test)]
mod tests {
    use std::{convert::Infallible, pin::pin};

    use futures::{future, stream};
    use teloxide_core::Bot;

    use super::*;
    use crate::{
        stop::{mk_stop_token, StopFlag, StopToken},
        update_listeners::StatefulListener,
    };

    fn update(id: u32) -> Update {
        let update: Update = serde_json::from_value(serde_json::json!({
            "update_id": id,
            "message": {"message_id": 1, "date": 0, "chat": {"id": 1, "type": "private"}}
        }))
        .unwrap();
        assert!(matches!(update.kind, UpdateKind::Message(_)), "{update:?}");
        update
    }

    fn listener(
        updates: impl futures::Stream<Item = Result<Update, Infallible>> + Send + 'static,
    ) -> (impl UpdateListener<Err = Infallible> + Send, StopFlag) {
        let (token, flag) = mk_stop_token();
        let stop = flag.clone();
        let listener = StatefulListener::new(
            (Some(updates.take_until(stop)), token),
            |state: &mut (Option<_>, StopToken)| state.0.take().unwrap(),
            |state: &mut (Option<_>, StopToken)| state.1.clone(),
        );
        (listener, flag)
    }

    #[tokio::test]
    async fn cancelling_dispatch_aborts_workers_and_allows_another_run() {
        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
        let handler = dptree::endpoint(move || {
            let tx = started_tx.clone();
            async move {
                // Dropped when the in-flight handler is aborted.
                let (alive_tx, alive_rx) = tokio::sync::oneshot::channel::<()>();
                tx.send(alive_rx).unwrap();
                let _alive = alive_tx;
                future::pending::<Result<(), Infallible>>().await
            }
        });
        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler).build();
        let shutdown = dispatcher.shutdown_token();
        for draining in [false, true] {
            let updates = stream::iter([Ok(update(1))]).chain(stream::poll_fn(move |_| {
                if draining {
                    std::task::Poll::Ready(None)
                } else {
                    std::task::Poll::Pending
                }
            }));
            let (listener, flag) = listener(updates);

            let completion;
            let alive;
            {
                let mut run =
                    pin!(dispatcher.start_listening(listener, LoggingErrorHandler::new()));
                alive = tokio::select! {
                    alive = started_rx.recv() => alive.unwrap(),
                    () = &mut run => panic!("dispatcher returned before its worker finished"),
                };
                // Test cancellation both while receiving and while draining workers.
                completion = draining.then(|| shutdown.shutdown().unwrap());
            }
            assert!(flag.is_stopped());
            assert!(shutdown.shutdown().is_err());
            if let Some(completion) = completion {
                completion.await;
            }
            assert!(alive.await.is_err());
        }

        let (listener, _) = self::listener(stream::empty());
        dispatcher.start_listening(listener, LoggingErrorHandler::new()).await;
    }

    #[tokio::test]
    async fn blocked_keyless_handler_backpressures_the_listener() {
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let release = release_rx.map(|result| result.unwrap()).shared();
        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
        let handler = dptree::endpoint(move |update: Update| {
            let started_tx = started_tx.clone();
            let release = release.clone();
            async move {
                started_tx.send(update.id.0).unwrap();
                release.await;
                Ok::<_, Infallible>(())
            }
        });
        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler)
            .distribution_function(|_| None::<()>)
            .worker_queue_size(1)
            .build();

        let reads = Arc::new(AtomicUsize::new(0));
        let (listener, _) = listener(stream::iter((1..=8).map({
            let reads = Arc::clone(&reads);
            move |id| {
                reads.fetch_add(1, Ordering::Relaxed);
                Ok(update(id))
            }
        })));
        let mut run = pin!(dispatcher.start_listening(listener, LoggingErrorHandler::new()));
        tokio::select! {
            id = started_rx.recv() => assert_eq!(id, Some(1)),
            () = &mut run => panic!("dispatcher returned while a handler was blocked"),
        }
        assert!(futures::poll!(&mut run).is_pending());
        assert_eq!(reads.load(Ordering::Relaxed), 1);
        release_tx.send(()).unwrap();
        run.await;
        assert_eq!(reads.load(Ordering::Relaxed), 8);
    }

    #[tokio::test]
    async fn worker_continues_after_handler_panic() {
        let (handled_tx, mut handled_rx) = mpsc::unbounded_channel();
        let handler = dptree::endpoint(move |update: Update| {
            let handled_tx = handled_tx.clone();
            async move {
                assert_ne!(update.id.0, 1, "broken handler");
                handled_tx.send(update.id.0).unwrap();
                Ok::<_, Infallible>(())
            }
        });
        let mut dispatcher = Dispatcher::builder(Bot::new(""), handler).build();
        let (listener, _) = listener(stream::iter([Ok(update(1)), Ok(update(2))]));
        dispatcher.start_listening(listener, LoggingErrorHandler::new()).await;
        assert_eq!(handled_rx.try_recv(), Ok(2));
    }

    #[tokio::test]
    async fn handler_error_receives_initial_dependencies() {
        let initial = dptree::deps!["configured"];
        let handler = dptree::map(|| 42_u32).endpoint(|| async { Err("handler failed") });
        let update = Update {
            id: crate::types::UpdateId(1),
            kind: UpdateKind::Error(serde_json::Value::Null),
        };
        let (tx, rx) = tokio::sync::oneshot::channel();
        let tx = std::sync::Mutex::new(Some(tx));
        let error_handler = move |err, deps: DependencyMap| {
            let tx = tx.lock().unwrap().take().unwrap();
            async move { tx.send((err, deps)).unwrap() }
        };

        handle_update(
            update,
            Arc::new(initial),
            Arc::new(handler),
            Arc::new(|_| unreachable!()),
            Arc::new(error_handler),
        )
        .await;

        let (err, deps) = rx.await.unwrap();
        assert_eq!(err, "handler failed");
        assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
        assert_eq!(deps.try_get::<Update>().unwrap().id, crate::types::UpdateId(1));
        assert!(deps.try_get::<u32>().is_none());
    }

    #[tokio::test]
    async fn listener_error_receives_initial_dependencies_without_current_update() {
        let dispatcher = Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
            .dependencies(dptree::deps!["configured"])
            .build();
        let error_handler = Arc::new(|err, deps: DependencyMap| async move {
            assert_eq!(err, "listener failed");
            assert_eq!(*deps.try_get::<&str>().unwrap(), "configured");
            assert!(deps.try_get::<Update>().is_none());
        });
        let mut workers = Workers::default();
        let permit = Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap();
        dispatcher
            .process_update(Err("listener failed"), &error_handler, &mut workers, permit)
            .await;
    }

    #[tokio::test]
    async fn test_tokio_spawn() {
        tokio::spawn(async {
            // Just check that this code compiles.
            if false {
                Dispatcher::<_, Infallible, _>::builder(Bot::new(""), dptree::entry())
                    .build()
                    .dispatch()
                    .await;
            }
        })
        .await
        .unwrap();
    }
}