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 },
);
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()
});
}
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,
) {
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! {
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,
};
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);
}
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();
}
}