mod request;
mod request_lock;
mod requester_impl;
mod settings;
mod worker;
use std::{
future::Future,
hash::{Hash, Hasher},
};
use tokio::sync::{
mpsc,
oneshot::{self},
};
use crate::{errors::AsResponseParameters, requests::Requester, types::*, RequestError};
use self::{
request_lock::{channel, RequestLock},
worker::{worker, FreezeUntil, InfoMessage},
};
pub use request::{ThrottlingRequest, ThrottlingSend};
pub use settings::{Limits, Settings};
#[derive(Clone, Debug)]
pub struct Throttle<B> {
bot: B,
queue: mpsc::Sender<(ChatIdHash, RequestLock)>,
info_tx: mpsc::Sender<InfoMessage>,
}
impl<B> Throttle<B> {
pub fn new(bot: B, limits: Limits) -> (Self, impl Future<Output = ()>)
where
B: Requester + Clone,
B::Err: AsResponseParameters,
{
let settings = Settings { limits, ..<_>::default() };
Self::with_settings(bot, settings)
}
pub fn with_settings(bot: B, settings: Settings) -> (Self, impl Future<Output = ()>)
where
B: Requester + Clone,
B::Err: AsResponseParameters,
{
let (tx, rx) =
mpsc::channel((settings.limits.messages_per_sec_overall as usize).clamp(2, 1024));
let (info_tx, info_rx) = mpsc::channel(2);
let worker = worker(settings, rx, info_rx, bot.clone());
let this = Self { bot, queue: tx, info_tx };
(this, worker)
}
pub fn new_spawn(bot: B, limits: Limits) -> Self
where
B: Requester + Clone + Send + Sync + 'static,
B::Err: AsResponseParameters,
B::GetChat: Send,
{
let (this, worker) = Self::new(bot, limits);
tokio::spawn(worker);
this
}
pub fn spawn_with_settings(bot: B, settings: Settings) -> Self
where
B: Requester + Clone + Send + Sync + 'static,
B::Err: AsResponseParameters,
B::GetChat: Send,
{
let (this, worker) = Self::with_settings(bot, settings);
tokio::spawn(worker);
this
}
pub fn inner(&self) -> &B {
&self.bot
}
pub fn into_inner(self) -> B {
self.bot
}
pub async fn limits(&self) -> Result<Limits, RequestError> {
let (tx, rx) = oneshot::channel();
self.info_tx
.send(InfoMessage::GetLimits { response: tx })
.await
.map_err(|_| RequestError::ThrottleWorkerStopped)?;
rx.await.map_err(|_| RequestError::ThrottleWorkerStopped)
}
pub async fn set_limits(&self, new: Limits) -> Result<(), RequestError> {
let (tx, rx) = oneshot::channel();
self.info_tx
.send(InfoMessage::SetLimits { new, response: tx })
.await
.map_err(|_| RequestError::ThrottleWorkerStopped)?;
rx.await.map_err(|_| RequestError::ThrottleWorkerStopped)
}
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
enum ChatIdHash {
Id(ChatId),
ChannelUsernameHash(u64),
Unknown,
}
impl ChatIdHash {
fn is_channel_or_supergroup(&self) -> bool {
match self {
&Self::Id(id) => id.is_channel_or_supergroup(),
Self::ChannelUsernameHash(_) => true,
Self::Unknown => false,
}
}
}
impl From<&ChatId> for ChatIdHash {
fn from(value: &ChatId) -> Self {
ChatIdHash::Id(*value)
}
}
impl From<&Recipient> for ChatIdHash {
fn from(value: &Recipient) -> Self {
match value {
Recipient::Id(id) => ChatIdHash::Id(*id),
Recipient::ChannelUsername(username) => {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
username.hash(&mut hasher);
let hash = hasher.finish();
ChatIdHash::ChannelUsernameHash(hash)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{requests::Request, Bot};
#[tokio::test]
async fn forum_edit_delete_and_pin_requests_are_throttled_by_chat() {
async fn assert_queued<R: Request>(
request: ThrottlingRequest<R>,
queue: &mut mpsc::Receiver<(ChatIdHash, RequestLock)>,
chat: ChatId,
) where
ThrottlingRequest<R>: Request,
{
assert!(futures::poll!(std::pin::pin!(request.send())).is_pending());
let (queued_chat, _lock) = queue.try_recv().expect("request must enter throttle queue");
assert_eq!(queued_chat, ChatIdHash::Id(chat));
}
let (tx, mut queue) = mpsc::channel(1);
let (info_tx, _) = mpsc::channel(1);
let bot = Throttle { bot: Bot::new("123:test"), queue: tx, info_tx };
let chat = ChatId(-1000000000001);
let message = MessageId(10);
let thread = ThreadId(message);
let media = InputMedia::Photo(InputMediaPhoto::new(InputFile::file_id("photo".into())));
assert_queued(bot.create_forum_topic(chat, "topic"), &mut queue, chat).await;
assert_queued(bot.edit_forum_topic(chat, thread), &mut queue, chat).await;
assert_queued(bot.delete_forum_topic(chat, thread), &mut queue, chat).await;
assert_queued(bot.pin_chat_message(chat, message), &mut queue, chat).await;
assert_queued(bot.edit_message_text(chat, message), &mut queue, chat).await;
assert_queued(bot.edit_message_caption(chat, message), &mut queue, chat).await;
assert_queued(bot.edit_message_media(chat, message, media), &mut queue, chat).await;
assert_queued(bot.delete_message(chat, message), &mut queue, chat).await;
assert_queued(bot.delete_messages(chat, [message]), &mut queue, chat).await;
}
}