teloxide-fork-core 0.16.0

Core part of the `teloxide` library - telegram bot API client
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
use std::{
    collections::{HashMap, VecDeque},
    time::{Duration, Instant},
};

use futures::{stream::FuturesUnordered, StreamExt};
use tokio::sync::{mpsc, oneshot};

use crate::{
    adaptors::throttle::{
        request_lock::{Permit, RequestLock},
        ChatIdHash, Limits, Settings,
    },
    requests::Requester,
};

const MINUTE: Duration = Duration::from_secs(60);
const SECOND: Duration = Duration::from_secs(1);
const DELAY: Duration = Duration::from_millis(250);
const QUEUE_FULL_DELAY: Duration = Duration::from_secs(4);
const SLOW_MODE_TTL: Duration = Duration::from_secs(30 * 60);

type QueuedChats = HashMap<ChatIdHash, ChatQueue>;

#[derive(Debug)]
pub(super) enum InfoMessage {
    GetLimits { response: oneshot::Sender<Limits> },
    SetLimits { new: Limits, response: oneshot::Sender<()> },
}

pub(super) struct FreezeUntil {
    pub(super) until: Instant,
    pub(super) after: Duration,
    pub(super) chat: ChatIdHash,
}

#[derive(Default)]
struct ChatQueue {
    pending: VecDeque<RequestLock>,
    turn: u64,
    in_flight: bool,
}

struct SlowMode {
    interval: Duration,
    next_allowed: Instant,
    expires: Instant,
}

fn apply_retry_after(
    event: FreezeUntil,
    interval: Option<Duration>,
    now: Instant,
    slow_mode: &mut HashMap<ChatIdHash, SlowMode>,
    global_until: &mut Instant,
) {
    if let Some(interval) = interval.filter(|interval| !interval.is_zero()) {
        slow_mode.insert(
            event.chat,
            SlowMode { interval, next_allowed: event.until, expires: now + SLOW_MODE_TTL },
        );
        // A current slow-mode setting can explain this retry only if the retry
        // delay fits within the interval. Stale settings never skip a global freeze.
        if event.after <= interval {
            return;
        }
    } else {
        slow_mode.remove(&event.chat);
    }
    *global_until = (*global_until).max(event.until);
}

fn prune_queues(queues: &mut QueuedChats) {
    queues.retain(|_, chat| {
        chat.pending.retain(|lock| !lock.is_cancelled());
        chat.in_flight || !chat.pending.is_empty()
    });
}

/// Each chat owns its FIFO through completion; a retry goes back in front of
/// that same chat's pending requests, without using the bounded ingress
/// channel.
pub(super) async fn worker<B: Requester>(
    Settings { mut limits, mut on_queue_full, retry, check_slow_mode }: Settings,
    mut rx: mpsc::Receiver<(ChatIdHash, RequestLock)>,
    mut info_rx: mpsc::Receiver<InfoMessage>,
    bot: B,
) {
    // Budget from the original settings. Reserve at least half of the global
    // queue for other chats by limiting each chat's share. Reject on saturation
    // rather than parking the sole ingress on a full chat.
    let max_pending = rx.max_capacity();
    let max_per_chat = max_pending / 2;
    let mut queues = QueuedChats::new();
    let mut turn = 0u64;
    let mut history: VecDeque<(ChatIdHash, Instant)> = VecDeque::new();
    let mut completions = FuturesUnordered::new();
    let mut lookups = FuturesUnordered::new();
    let mut slow_mode = HashMap::<ChatIdHash, SlowMode>::new();
    let mut global_until = Instant::now();
    let mut last_full = None::<Instant>;
    let mut rx_open = true;
    let mut info_open = true;
    let mut tick = tokio::time::interval(DELAY);
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

    loop {
        prune_queues(&mut queues);
        if !rx_open && queues.is_empty() {
            return;
        }

        tokio::select! {
            // Process received 429s before granting further permits.
            biased;
            Some((chat, result)) = completions.next(), if !completions.is_empty() => {
                let queue = queues.get_mut(&chat).unwrap();
                queue.in_flight = false;
                if let Ok((event, next_lock)) = result {
                    if let Some(lock) = next_lock {
                        queue.pending.push_front(lock);
                    }
                    if check_slow_mode {
                        if let ChatIdHash::Id(id) = chat {
                            let request = bot.get_chat(id);
                            lookups.push(async move {
                                let interval = request.await.ok().and_then(|chat| chat.slow_mode_delay());
                                (event, interval.map(|value| value.duration()))
                            });
                            continue;
                        }
                    }
                    apply_retry_after(event, None, Instant::now(), &mut slow_mode, &mut global_until);
                }
            }
            Some((event, interval)) = lookups.next(), if !lookups.is_empty() => {
                apply_retry_after(event, interval, Instant::now(), &mut slow_mode, &mut global_until);
            }
            info = info_rx.recv(), if info_open => {
                match info {
                    Some(InfoMessage::GetLimits { response }) => { let _ = response.send(limits); }
                    Some(InfoMessage::SetLimits { new, response }) => {
                        limits = new;
                        let _ = response.send(());
                    }
                    None => info_open = false,
                }
            }
            _ = tick.tick(), if !queues.is_empty() || !history.is_empty() || !slow_mode.is_empty() => {
                let now = Instant::now();
                slow_mode.retain(|_, mode| now < mode.expires);
                while history.front().is_some_and(|(_, sent)| now.duration_since(*sent) >= MINUTE) {
                    history.pop_front();
                }
                if now < global_until || !lookups.is_empty() || queues.is_empty() {
                    continue;
                }
                let mut per_min = HashMap::<ChatIdHash, u32>::new();
                let mut per_sec = HashMap::<ChatIdHash, u32>::new();
                let mut overall = 0u32;
                for (chat, sent) in &history {
                    *per_min.entry(*chat).or_default() += 1;
                    if now.duration_since(*sent) < SECOND {
                        *per_sec.entry(*chat).or_default() += 1;
                        overall += 1;
                    }
                }
                let mut chats: Vec<_> = queues.iter_mut().collect();
                chats.sort_unstable_by_key(|(_, queue)| queue.turn);
                for (&chat, queue) in chats {
                    if overall >= limits.messages_per_sec_overall {
                        break;
                    }
                    if queue.in_flight || queue.pending.is_empty()
                        || slow_mode.get(&chat).is_some_and(|mode| mode.next_allowed > now)
                    {
                        continue;
                    }
                    let per_min_limit = if chat.is_channel_or_supergroup() {
                        limits.messages_per_min_channel_or_supergroup
                    } else {
                        limits.messages_per_min_chat
                    };
                    if per_sec.get(&chat).copied().unwrap_or(0) >= limits.messages_per_sec_chat
                        || per_min.get(&chat).copied().unwrap_or(0) >= per_min_limit
                    {
                        continue;
                    }
                    if let Some(lock) = queue.pending.pop_front() {
                        let (finished, completion) = oneshot::channel();
                        if lock.unlock(Permit { retry, finished }) {
                            queue.in_flight = true;
                            completions.push(async move { (chat, completion.await) });
                            history.push_back((chat, now));
                            if let Some(mode) = slow_mode.get_mut(&chat) {
                                mode.next_allowed = now + mode.interval;
                            }
                            queue.turn = turn;
                            turn += 1;
                            overall += 1;
                        }
                    }
                }
            }
            request = rx.recv(), if rx_open => {
                if let Some((chat, lock)) = request {
                    if lock.is_cancelled() {
                        continue;
                    }
                    let queued = |q: &ChatQueue| q.pending.len() + usize::from(q.in_flight);
                    let pending: usize = queues.values().map(queued).sum();
                    if pending >= max_pending || queues.get(&chat).is_some_and(|q| queued(q) >= max_per_chat) {
                        let now = Instant::now();
                        if last_full.is_none_or(|last| now.duration_since(last) >= QUEUE_FULL_DELAY) {
                            last_full = Some(now);
                            tokio::spawn(on_queue_full(pending));
                        }
                        lock.reject();
                    } else {
                        let queue = queues.entry(chat).or_insert_with(|| {
                            let queue = ChatQueue { turn, ..ChatQueue::default() };
                            turn += 1;
                            queue
                        });
                        queue.pending.push_back(lock);
                    }
                } else {
                    rx_open = false;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{
        io::{Read, Write},
        net::TcpListener,
        sync::{
            atomic::{AtomicBool, AtomicUsize, Ordering},
            Arc,
        },
        thread,
    };

    use serde_json::{json, Value};

    use crate::{
        adaptors::throttle::{channel, worker::*, Throttle},
        payloads::SendMessageSetters,
        requests::{Request, Requester},
        types::ChatId,
        Bot,
    };

    // Exercise the real Bot API serialization/deserialization without another mock
    // dependency. Every connection receives the configured getChat response.
    struct MockApi {
        bot: Bot,
        calls: Arc<AtomicUsize>,
        stop: Arc<AtomicBool>,
        thread: Option<thread::JoinHandle<()>>,
    }

    impl MockApi {
        fn new(response: Value) -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let address = listener.local_addr().unwrap();
            listener.set_nonblocking(true).unwrap();
            let calls = Arc::new(AtomicUsize::new(0));
            let stop = Arc::new(AtomicBool::new(false));
            let thread = {
                let calls = Arc::clone(&calls);
                let stop = Arc::clone(&stop);
                thread::spawn(move || {
                    while !stop.load(Ordering::SeqCst) {
                        let (mut stream, _) = match listener.accept() {
                            Ok(connection) => connection,
                            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                                thread::sleep(Duration::from_millis(1));
                                continue;
                            }
                            Err(error) => panic!("mock accept: {error}"),
                        };
                        stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
                        let mut request = Vec::new();
                        let mut buffer = [0; 4096];
                        loop {
                            let n = stream.read(&mut buffer).unwrap();
                            assert_ne!(n, 0);
                            request.extend_from_slice(&buffer[..n]);
                            if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
                                let headers = String::from_utf8_lossy(&request[..end]);
                                let length: usize = headers
                                    .lines()
                                    .find_map(|line| {
                                        line.to_ascii_lowercase()
                                            .strip_prefix("content-length:")
                                            .map(|n| n.trim().parse().unwrap())
                                    })
                                    .unwrap_or(0);
                                if request.len() >= end + 4 + length {
                                    let path = headers.lines().next().unwrap();
                                    assert!(
                                        path.contains("/GetChat") || path.contains("/SendMessage")
                                    );
                                    break;
                                }
                            }
                        }
                        calls.fetch_add(1, Ordering::SeqCst);
                        let body = response.to_string();
                        write!(
                            stream,
                            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: \
                             {}\r\nConnection: close\r\n\r\n{body}",
                            body.len()
                        )
                        .unwrap();
                    }
                })
            };
            Self {
                bot: Bot::new("123:test")
                    .set_api_url(format!("http://{address}/").parse().unwrap()),
                calls,
                stop,
                thread: Some(thread),
            }
        }
    }

    impl Drop for MockApi {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::SeqCst);
            self.thread.take().unwrap().join().unwrap();
        }
    }

    fn chat_response(delay: Option<u32>) -> Value {
        let mut chat = json!({
            "id": -1000000000001_i64, "type": "supergroup", "title": "slow chat",
            "max_reaction_count": 1,
            "accepted_gift_types": {
                "unlimited_gifts": false, "limited_gifts": false,
                "unique_gifts": false, "premium_subscription": false
            }
        });
        if let Some(delay) = delay {
            chat["slow_mode_delay"] = json!(delay);
        }
        // Fail clearly if a fixture no longer represents a valid API response.
        serde_json::from_value::<crate::types::ChatFullInfo>(chat.clone()).unwrap();
        json!({"ok": true, "result": chat})
    }

    const CHAT: ChatIdHash = ChatIdHash::Id(ChatId(-1000000000001));

    #[test]
    fn short_slow_mode_retry_waits_only_its_remaining_second() {
        let now = Instant::now();
        let mut global = now;
        let mut cache = HashMap::new();
        apply_retry_after(
            FreezeUntil { until: now + SECOND, after: SECOND, chat: CHAT },
            Some(Duration::from_secs(900)),
            now,
            &mut cache,
            &mut global,
        );
        assert_eq!(global, now);
        assert_eq!(cache[&CHAT].next_allowed, now + SECOND);
        assert_eq!(cache[&CHAT].interval, Duration::from_secs(900));
    }

    #[test]
    fn stale_missing_or_insufficient_slow_mode_does_not_explain_global_429() {
        let now = Instant::now();
        for interval in [None, Some(Duration::ZERO), Some(SECOND)] {
            let mut global = now;
            let mut cache = HashMap::from([(
                CHAT,
                SlowMode {
                    interval: Duration::from_secs(900),
                    next_allowed: now,
                    expires: now + SLOW_MODE_TTL,
                },
            )]);
            let after = Duration::from_secs(2);
            apply_retry_after(
                FreezeUntil { until: now + after, after, chat: CHAT },
                interval,
                now,
                &mut cache,
                &mut global,
            );
            assert_eq!(global, now + after);
            assert_eq!(
                cache.get(&CHAT).map(|mode| mode.interval),
                interval.filter(|delay| !delay.is_zero())
            );
        }
    }

    async fn enqueue(
        bot: &Throttle<Bot>,
        chat: ChatIdHash,
    ) -> oneshot::Receiver<Result<Permit, crate::RequestError>> {
        let (lock, wait) = channel();
        bot.queue.send((chat, lock)).await.unwrap();
        wait
    }

    #[tokio::test]
    async fn worker_retries_head_before_next_and_serves_other_chats() {
        let api = MockApi::new(chat_response(Some(900)));
        let (bot, worker) =
            Throttle::with_settings(api.bot.clone(), Settings::default().check_slow_mode());
        let worker = tokio::spawn(worker);
        assert_eq!(bot.limits().await.unwrap(), Limits::default());
        let first = enqueue(&bot, CHAT).await.await.unwrap().unwrap();
        let (lock, retry_wait) = channel();
        let mut next = enqueue(&bot, CHAT).await;
        let until = Instant::now() + SECOND;
        assert!(first
            .finished
            .send((FreezeUntil { until, after: SECOND, chat: CHAT }, Some(lock)))
            .is_ok());
        let other = enqueue(&bot, ChatIdHash::Id(ChatId(i64::MIN))).await;
        let other = tokio::time::timeout(Duration::from_millis(800), other)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        drop(other);
        let retry = tokio::time::timeout(Duration::from_secs(3), retry_wait)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert!(Instant::now() >= until);
        drop(retry);
        assert!(tokio::time::timeout(Duration::from_millis(300), &mut next).await.is_err());
        assert_eq!(api.calls.load(Ordering::SeqCst), 1);
        worker.abort();
        assert!(next.await.is_err());
    }

    #[tokio::test]
    async fn control_is_serviced_during_global_freeze_and_shutdown_is_an_error() {
        let api = MockApi::new(json!({"ok": true, "result": true}));
        let (bot, worker) = Throttle::new(api.bot.clone(), Limits::default());
        let worker = tokio::spawn(worker);
        let first = enqueue(&bot, CHAT).await.await.unwrap().unwrap();
        let after = Duration::from_secs(60);
        assert!(first
            .finished
            .send((FreezeUntil { until: Instant::now() + after, after, chat: CHAT }, None))
            .is_ok());
        let mut pending = Box::pin(bot.send_message("pending").chat_id(ChatId(2)).send());
        assert!(futures::poll!(&mut pending).is_pending());
        let limits = Limits { messages_per_sec_overall: 5, ..Default::default() };
        tokio::time::timeout(SECOND, bot.set_limits(limits)).await.unwrap().unwrap();
        assert_eq!(bot.limits().await.unwrap(), limits);
        worker.abort();
        let _ = worker.await;
        assert!(matches!(pending.await, Err(crate::RequestError::ThrottleWorkerStopped)));
        assert!(matches!(
            bot.send_message("new").chat_id(ChatId(2)).await,
            Err(crate::RequestError::ThrottleWorkerStopped)
        ));
        assert_eq!(api.calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn saturated_chat_cannot_take_other_chats_slots() {
        let api = MockApi::new(json!({"ok": true, "result": true}));
        let limits = Limits { messages_per_sec_overall: 4, ..Default::default() };
        let (bot, worker) = Throttle::new(api.bot.clone(), limits);
        let worker = tokio::spawn(worker);
        let first = enqueue(&bot, CHAT).await.await.unwrap().unwrap();
        let cancelled = enqueue(&bot, CHAT).await;
        drop(cancelled);
        let _pending = enqueue(&bot, CHAT).await;
        assert!(matches!(
            enqueue(&bot, CHAT).await.await.unwrap(),
            Err(crate::RequestError::ThrottleQueueFull)
        ));
        assert!(tokio::time::timeout(SECOND, enqueue(&bot, ChatIdHash::Id(ChatId(2))).await)
            .await
            .unwrap()
            .unwrap()
            .is_ok());
        drop(first);
        worker.abort();
    }
}