rust-tg-bot-ext 1.0.0-rc.1

Application framework for Telegram bots -- handlers, filters, persistence, job queue
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
//! Extended bot with convenience features.
//!
//! Ported from `python-telegram-bot/src/telegram/ext/_extbot.py`.
//!
//! [`ExtBot`] wraps the low-level [`rust_tg_bot_raw::bot::Bot`] and adds:
//!
//! * [`Defaults`](crate::defaults::Defaults) injection into API calls
//! * [`CallbackDataCache`](crate::callback_data_cache::CallbackDataCache) for arbitrary
//!   callback data
//! * A [`DynRateLimiter`](crate::rate_limiter::DynRateLimiter) that intercepts all HTTP
//!   requests through a [`RateLimitedRequest`](crate::rate_limiter::RateLimitedRequest)
//!   wrapper.
//!
//! # Construction
//!
//! Use [`ExtBot::builder`] for the full option set, or [`ExtBot::from_bot`] when you
//! only have a raw `Bot` and need no extras:
//!
//! ```rust,ignore
//! // Minimal:
//! let ext = ExtBot::from_bot(bot);
//!
//! // Full control:
//! let ext = ExtBot::builder("token", request)
//!     .defaults(defaults)
//!     .arbitrary_callback_data(512)
//!     .rate_limiter(Arc::new(AioRateLimiter::default_limits()))
//!     .build();
//! ```
//!
//! # Rate limiting
//!
//! When a rate limiter is provided, the builder wraps the HTTP request backend
//! in a [`RateLimitedRequest`](crate::rate_limiter::RateLimitedRequest), so
//! **all** API calls flow through the limiter transparently.  No changes to
//! handler code are needed.
//!
//! # `Deref` to `Bot`
//!
//! `ExtBot` implements `Deref<Target = Bot>`, so all `Bot` methods are accessible
//! directly without calling `.inner()`:
//!
//! ```rust,ignore
//! // Instead of: ext_bot.inner().send_message(chat_id, text)
//! ext_bot.send_message(chat_id, text)
//! ```

use std::sync::Arc;

use tokio::sync::RwLock;

use rust_tg_bot_raw::bot::Bot;
use rust_tg_bot_raw::request::base::BaseRequest;

use crate::callback_data_cache::CallbackDataCache;
use crate::defaults::Defaults;

#[cfg(feature = "rate-limiter")]
use crate::rate_limiter::{DynRateLimiter, RateLimitedRequest};

/// Extended bot that adds defaults, arbitrary callback data, and a rate-limiter slot on top
/// of the raw [`Bot`].
///
/// # Construction
///
/// Use [`ExtBot::builder`] for the full option set, or [`ExtBot::from_bot`] for the
/// simplest case (no defaults, no cache, no rate limiter).
///
/// # `Deref` to `Bot`
///
/// `ExtBot` implements [`Deref<Target = Bot>`](std::ops::Deref), making all `Bot` methods
/// accessible directly. This is a zero-cost abstraction -- no allocation or indirection
/// beyond what `Bot` already provides.
///
/// # Rate limiter
///
/// When a rate limiter is set, the inner `Bot`'s HTTP request backend is wrapped in a
/// [`RateLimitedRequest`](crate::rate_limiter::RateLimitedRequest) so that all API calls
/// are throttled transparently at the transport layer.
pub struct ExtBot {
    /// The underlying raw bot.
    bot: Bot,

    /// User-defined defaults for API calls.
    defaults: Option<Defaults>,

    /// Cache for arbitrary inline keyboard callback data.
    callback_data_cache: Option<Arc<RwLock<CallbackDataCache>>>,

    /// The rate limiter, if any.  Stored here for introspection; the actual
    /// throttling is done by the `RateLimitedRequest` wrapper inside `bot`.
    #[cfg(feature = "rate-limiter")]
    rate_limiter: Option<Arc<dyn DynRateLimiter>>,

    /// Placeholder when the rate-limiter feature is disabled.
    #[cfg(not(feature = "rate-limiter"))]
    rate_limiter: Option<()>,
}

// ---------------------------------------------------------------------------
// Deref<Target = Bot> -- zero-cost access to all Bot methods
// ---------------------------------------------------------------------------

impl std::ops::Deref for ExtBot {
    type Target = Bot;

    fn deref(&self) -> &Bot {
        &self.bot
    }
}

impl std::fmt::Debug for ExtBot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExtBot")
            .field("token", &self.bot.token())
            .field("defaults", &self.defaults)
            .field(
                "has_callback_data_cache",
                &self.callback_data_cache.is_some(),
            )
            .field("has_rate_limiter", &self.rate_limiter.is_some())
            .finish()
    }
}

impl ExtBot {
    /// Creates a new `ExtBot`.
    ///
    /// # Arguments
    ///
    /// * `bot` - The underlying raw bot.
    /// * `defaults` - Optional user-defined defaults for API calls.
    /// * `arbitrary_callback_data` - Pass `Some(maxsize)` to enable the callback data cache,
    ///   or `None` to disable it.  `Some(0)` uses the default maxsize of 1024.
    /// * `rate_limiter` - An optional rate limiter.  When `Some`, the bot's request backend
    ///   is wrapped in a `RateLimitedRequest` so all API calls are throttled.
    ///
    /// Prefer [`ExtBot::builder`] or [`ExtBot::from_bot`] for public construction.
    #[cfg(feature = "rate-limiter")]
    #[must_use]
    pub(crate) fn new(
        bot: Bot,
        defaults: Option<Defaults>,
        arbitrary_callback_data: Option<usize>,
        rate_limiter: Option<Arc<dyn DynRateLimiter>>,
    ) -> Self {
        let callback_data_cache = arbitrary_callback_data.map(|maxsize| {
            let effective = if maxsize == 0 { 1024 } else { maxsize };
            Arc::new(RwLock::new(CallbackDataCache::new(effective)))
        });

        Self {
            bot,
            defaults,
            callback_data_cache,
            rate_limiter,
        }
    }

    /// Creates a new `ExtBot` (no rate-limiter feature).
    #[cfg(not(feature = "rate-limiter"))]
    #[must_use]
    pub(crate) fn new(
        bot: Bot,
        defaults: Option<Defaults>,
        arbitrary_callback_data: Option<usize>,
        rate_limiter: Option<()>,
    ) -> Self {
        let callback_data_cache = arbitrary_callback_data.map(|maxsize| {
            let effective = if maxsize == 0 { 1024 } else { maxsize };
            Arc::new(RwLock::new(CallbackDataCache::new(effective)))
        });

        Self {
            bot,
            defaults,
            callback_data_cache,
            rate_limiter,
        }
    }

    /// Creates an `ExtBot` from a raw `Bot` with no extras.
    ///
    /// This is the simplest construction path -- no defaults, no callback data
    /// cache, and no rate limiter.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let bot = Bot::new("token", request);
    /// let ext = ExtBot::from_bot(bot);
    /// ```
    #[must_use]
    pub fn from_bot(bot: Bot) -> Self {
        Self::new(bot, None, None, None)
    }

    /// Returns a reference to the underlying raw bot.
    ///
    /// Note: With the `Deref<Target = Bot>` implementation, you can call `Bot`
    /// methods directly on `ExtBot` without using `.inner()`. This method is
    /// retained for backward compatibility.
    #[must_use]
    pub fn inner(&self) -> &Bot {
        &self.bot
    }

    /// Returns the bot token (delegates to the inner bot).
    #[must_use]
    pub fn token(&self) -> &str {
        self.bot.token()
    }

    /// Returns the user-defined defaults, if any.
    #[must_use]
    pub fn defaults(&self) -> Option<&Defaults> {
        self.defaults.as_ref()
    }

    /// Returns a reference to the callback data cache, if enabled.
    #[must_use]
    pub fn callback_data_cache(&self) -> Option<&Arc<RwLock<CallbackDataCache>>> {
        self.callback_data_cache.as_ref()
    }

    /// Returns `true` if arbitrary callback data is enabled.
    #[must_use]
    pub fn has_callback_data_cache(&self) -> bool {
        self.callback_data_cache.is_some()
    }

    /// Returns `true` if a rate limiter is configured.
    #[must_use]
    pub fn has_rate_limiter(&self) -> bool {
        self.rate_limiter.is_some()
    }

    /// Returns a reference to the rate limiter, if set.
    #[cfg(feature = "rate-limiter")]
    #[must_use]
    pub fn rate_limiter(&self) -> Option<&Arc<dyn DynRateLimiter>> {
        self.rate_limiter.as_ref()
    }

    /// Returns the rate-limiter placeholder (always `None` when feature is disabled).
    #[cfg(not(feature = "rate-limiter"))]
    #[must_use]
    pub fn rate_limiter(&self) -> Option<()> {
        self.rate_limiter
    }

    /// Convenience builder entry point.
    #[must_use]
    pub fn builder(token: impl Into<String>, request: Arc<dyn BaseRequest>) -> ExtBotBuilder {
        ExtBotBuilder::new(token, request)
    }

    /// Initializes the bot.
    ///
    /// If a rate limiter is present, it is initialized here.
    pub async fn initialize(&self) -> rust_tg_bot_raw::error::Result<()> {
        #[cfg(feature = "rate-limiter")]
        if let Some(ref rl) = self.rate_limiter {
            rl.initialize().await;
        }
        Ok(())
    }

    /// Shuts down the bot.
    ///
    /// If a rate limiter is present, it is shut down here.
    pub async fn shutdown(&self) -> rust_tg_bot_raw::error::Result<()> {
        #[cfg(feature = "rate-limiter")]
        if let Some(ref rl) = self.rate_limiter {
            rl.shutdown().await;
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// ExtBotBuilder
// ---------------------------------------------------------------------------

/// Builder for [`ExtBot`].
///
/// # Example
///
/// ```rust,ignore
/// let ext = ExtBot::builder("my_token", request)
///     .defaults(defaults)
///     .arbitrary_callback_data(256)
///     .rate_limiter(Arc::new(AioRateLimiter::default_limits()))
///     .build();
/// ```
pub struct ExtBotBuilder {
    token: String,
    request: Arc<dyn BaseRequest>,
    base_url: Option<String>,
    base_file_url: Option<String>,
    defaults: Option<Defaults>,
    arbitrary_callback_data: Option<usize>,
    #[cfg(feature = "rate-limiter")]
    rate_limiter: Option<Arc<dyn DynRateLimiter>>,
    #[cfg(not(feature = "rate-limiter"))]
    rate_limiter: Option<()>,
}

impl ExtBotBuilder {
    /// Creates a new builder with the required token and HTTP request backend.
    #[must_use]
    pub fn new(token: impl Into<String>, request: Arc<dyn BaseRequest>) -> Self {
        Self {
            token: token.into(),
            request,
            base_url: None,
            base_file_url: None,
            defaults: None,
            arbitrary_callback_data: None,
            rate_limiter: None,
        }
    }

    /// Sets a custom base URL (e.g. for a local Bot API server).
    #[must_use]
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Sets a custom base file URL.
    #[must_use]
    pub fn base_file_url(mut self, url: impl Into<String>) -> Self {
        self.base_file_url = Some(url.into());
        self
    }

    /// Sets the user-defined defaults.
    #[must_use]
    pub fn defaults(mut self, defaults: Defaults) -> Self {
        self.defaults = Some(defaults);
        self
    }

    /// Enables arbitrary callback data with the given cache size.
    ///
    /// Pass `0` to use the default maxsize of 1024.
    #[must_use]
    pub fn arbitrary_callback_data(mut self, maxsize: usize) -> Self {
        self.arbitrary_callback_data = Some(maxsize);
        self
    }

    /// Sets the rate limiter.
    ///
    /// When set, the builder wraps the request backend in a
    /// [`RateLimitedRequest`](crate::rate_limiter::RateLimitedRequest) so all
    /// API calls are throttled transparently.
    #[cfg(feature = "rate-limiter")]
    #[must_use]
    pub fn rate_limiter(mut self, rl: Arc<dyn DynRateLimiter>) -> Self {
        self.rate_limiter = Some(rl);
        self
    }

    /// Sets the rate-limiter placeholder (feature disabled).
    #[cfg(not(feature = "rate-limiter"))]
    #[must_use]
    pub fn rate_limiter(mut self, _rl: ()) -> Self {
        self.rate_limiter = Some(());
        self
    }

    /// Builds the [`ExtBot`].
    ///
    /// If a rate limiter was provided, the HTTP request backend is wrapped in a
    /// `RateLimitedRequest` before being passed to the inner `Bot`.
    #[must_use]
    pub fn build(self) -> ExtBot {
        #[cfg(feature = "rate-limiter")]
        let (request, rate_limiter) = if let Some(ref rl) = self.rate_limiter {
            let wrapped: Arc<dyn BaseRequest> =
                Arc::new(RateLimitedRequest::new(self.request.clone(), rl.clone()));
            (wrapped, self.rate_limiter)
        } else {
            (self.request, None)
        };

        #[cfg(not(feature = "rate-limiter"))]
        let (request, rate_limiter) = (self.request, self.rate_limiter);

        let bot = Bot::new(&self.token, request);

        ExtBot::new(
            bot,
            self.defaults,
            self.arbitrary_callback_data,
            rate_limiter,
        )
    }
}

impl std::fmt::Debug for ExtBotBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExtBotBuilder")
            .field("token", &"[REDACTED]")
            .field("has_rate_limiter", &self.rate_limiter.is_some())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Test-only mock request
// ---------------------------------------------------------------------------

/// A minimal mock [`BaseRequest`] for use in tests throughout the ext crate.
///
/// Returns `{"ok": true, "result": []}` for every request.
#[cfg(test)]
pub(crate) mod test_support {
    use std::time::Duration;

    use rust_tg_bot_raw::request::base::{HttpMethod, TimeoutOverride};
    use rust_tg_bot_raw::request::request_data::RequestData;

    use super::*;

    #[derive(Debug)]
    pub struct MockRequest;

    #[async_trait::async_trait]
    impl BaseRequest for MockRequest {
        async fn initialize(&self) -> rust_tg_bot_raw::error::Result<()> {
            Ok(())
        }

        async fn shutdown(&self) -> rust_tg_bot_raw::error::Result<()> {
            Ok(())
        }

        fn default_read_timeout(&self) -> Option<Duration> {
            Some(Duration::from_secs(5))
        }

        async fn do_request(
            &self,
            _url: &str,
            _method: HttpMethod,
            _request_data: Option<&RequestData>,
            _timeouts: TimeoutOverride,
        ) -> rust_tg_bot_raw::error::Result<(u16, bytes::Bytes)> {
            let body = br#"{"ok":true,"result":[]}"#;
            Ok((200, bytes::Bytes::from_static(body)))
        }

        async fn do_request_json_bytes(
            &self,
            _url: &str,
            _body: &[u8],
            _timeouts: TimeoutOverride,
        ) -> rust_tg_bot_raw::error::Result<(u16, bytes::Bytes)> {
            let body = br#"{"ok":true,"result":[]}"#;
            Ok((200, bytes::Bytes::from_static(body)))
        }
    }

    pub fn mock_request() -> Arc<dyn BaseRequest> {
        Arc::new(MockRequest)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_support::*;

    #[test]
    fn ext_bot_creation() {
        let bot = Bot::new("test_token", mock_request());
        let ext = ExtBot::from_bot(bot);

        assert_eq!(ext.token(), "test_token");
        assert!(ext.defaults().is_none());
        assert!(!ext.has_callback_data_cache());
        assert!(!ext.has_rate_limiter());
    }

    #[test]
    fn ext_bot_with_callback_cache() {
        let bot = Bot::new("token", mock_request());
        let ext = ExtBot::new(bot, None, Some(512), None);

        assert!(ext.has_callback_data_cache());
    }

    #[test]
    fn ext_bot_with_defaults() {
        let defaults = Defaults::builder().parse_mode("HTML").build();
        let bot = Bot::new("token", mock_request());
        let ext = ExtBot::new(bot, Some(defaults), None, None);

        assert_eq!(ext.defaults().unwrap().parse_mode(), Some("HTML"));
    }

    #[test]
    fn ext_bot_builder() {
        let ext = ExtBot::builder("my_token", mock_request())
            .arbitrary_callback_data(256)
            .build();

        assert_eq!(ext.token(), "my_token");
        assert!(ext.has_callback_data_cache());
    }

    #[tokio::test]
    async fn ext_bot_lifecycle() {
        let bot = Bot::new("token", mock_request());
        let ext = ExtBot::from_bot(bot);
        assert!(ext.initialize().await.is_ok());
        assert!(ext.shutdown().await.is_ok());
    }

    #[test]
    fn ext_bot_debug() {
        let bot = Bot::new("token", mock_request());
        let ext = ExtBot::from_bot(bot);
        let s = format!("{ext:?}");
        assert!(s.contains("ExtBot"));
        assert!(s.contains("token"));
    }

    #[test]
    fn ext_bot_from_bot_convenience() {
        let bot = Bot::new("tk", mock_request());
        let ext = ExtBot::from_bot(bot);
        assert_eq!(ext.token(), "tk");
        assert!(ext.defaults().is_none());
        assert!(!ext.has_callback_data_cache());
        assert!(!ext.has_rate_limiter());
    }

    #[test]
    fn ext_bot_deref_provides_bot_methods() {
        let bot = Bot::new("deref_token", mock_request());
        let ext = ExtBot::from_bot(bot);

        // token() is available on Bot via Deref (same as ext.inner().token())
        let deref_token: &str = (*ext).token();
        assert_eq!(deref_token, "deref_token");
        assert_eq!(ext.token(), deref_token);
    }

    #[cfg(feature = "rate-limiter")]
    #[test]
    fn ext_bot_builder_with_rate_limiter() {
        use crate::rate_limiter::NoRateLimiter;

        let limiter: Arc<dyn DynRateLimiter> = Arc::new(NoRateLimiter);
        let ext = ExtBot::builder("rl_token", mock_request())
            .rate_limiter(limiter)
            .build();

        assert_eq!(ext.token(), "rl_token");
        assert!(ext.has_rate_limiter());
        assert!(ext.rate_limiter().is_some());
    }

    #[cfg(feature = "rate-limiter")]
    #[test]
    fn ext_bot_builder_without_rate_limiter() {
        let ext = ExtBot::builder("no_rl", mock_request()).build();

        assert!(!ext.has_rate_limiter());
        assert!(ext.rate_limiter().is_none());
    }

    #[cfg(feature = "rate-limiter")]
    #[tokio::test]
    async fn ext_bot_lifecycle_with_rate_limiter() {
        use crate::rate_limiter::NoRateLimiter;

        let limiter: Arc<dyn DynRateLimiter> = Arc::new(NoRateLimiter);
        let ext = ExtBot::builder("rl_lc", mock_request())
            .rate_limiter(limiter)
            .build();

        assert!(ext.initialize().await.is_ok());
        assert!(ext.shutdown().await.is_ok());
    }
}