use std::{
future::IntoFuture,
pin::Pin,
sync::{Arc, RwLock},
};
use futures::{
future,
future::{ok, Ready},
task::{Context, Poll},
Future,
};
use once_cell::sync::OnceCell;
use url::Url;
use crate::{
payloads::GetMe,
requests::{HasPayload, Output, Request, Requester},
types::*,
};
#[derive(Clone, Debug)]
pub struct CacheMe<B> {
bot: B,
me: Arc<MeCache>,
}
#[derive(Debug, Default)]
struct MeCache(RwLock<Arc<OnceCell<BotFullInfo>>>);
impl MeCache {
fn current(&self) -> Arc<OnceCell<BotFullInfo>> {
Arc::clone(&self.0.read().unwrap_or_else(|err| err.into_inner()))
}
fn invalidate(&self) {
*self.0.write().unwrap_or_else(|err| err.into_inner()) = Arc::default();
}
}
impl<B> CacheMe<B> {
pub fn new(bot: B) -> CacheMe<B> {
Self { bot, me: Arc::default() }
}
pub fn inner(&self) -> &B {
&self.bot
}
pub fn into_inner(self) -> B {
self.bot
}
pub fn clear(&mut self) -> Option<BotFullInfo> {
let previous = self.me.current().get().cloned();
self.me = Arc::default();
previous
}
}
macro_rules! f {
($m:ident $this:ident ($($arg:ident : $T:ty),*)) => {
$this.inner().$m($($arg),*)
};
}
macro_rules! fty {
($T:ident) => {
B::$T
};
}
impl<B> Requester for CacheMe<B>
where
B: Requester,
{
type Err = B::Err;
type GetMe = CachedMeRequest<B::GetMe>;
fn get_me(&self) -> Self::GetMe {
CachedMeRequest(self.bot.get_me(), Arc::clone(&self.me))
}
type SetMySettings = InvalidateMeRequest<B::SetMySettings>;
fn set_my_settings(&self) -> Self::SetMySettings {
InvalidateMeRequest(self.bot.set_my_settings(), Arc::clone(&self.me))
}
type SetMyName = InvalidateMeRequest<B::SetMyName>;
fn set_my_name(&self) -> Self::SetMyName {
InvalidateMeRequest(self.bot.set_my_name(), Arc::clone(&self.me))
}
type SetMyDescription = InvalidateMeRequest<B::SetMyDescription>;
fn set_my_description(&self) -> Self::SetMyDescription {
InvalidateMeRequest(self.bot.set_my_description(), Arc::clone(&self.me))
}
type SetMyShortDescription = InvalidateMeRequest<B::SetMyShortDescription>;
fn set_my_short_description(&self) -> Self::SetMyShortDescription {
InvalidateMeRequest(self.bot.set_my_short_description(), Arc::clone(&self.me))
}
type SetMyProfilePhoto = InvalidateMeRequest<B::SetMyProfilePhoto>;
fn set_my_profile_photo(&self, photo: InputProfilePhoto) -> Self::SetMyProfilePhoto {
InvalidateMeRequest(self.bot.set_my_profile_photo(photo), Arc::clone(&self.me))
}
type RemoveMyProfilePhoto = InvalidateMeRequest<B::RemoveMyProfilePhoto>;
fn remove_my_profile_photo(&self) -> Self::RemoveMyProfilePhoto {
InvalidateMeRequest(self.bot.remove_my_profile_photo(), Arc::clone(&self.me))
}
requester_forward! {
send_widget,
send_shared_widget,
get_chat_share_theme_backdrops,
answer_widget_query,
get_unique_gift,
delete_business_account_gift,
edit_message_widget_data,
edit_message_widget_data_inline,
edit_shared_widget_data,
log_out,
close,
get_updates,
set_webhook,
delete_webhook,
get_webhook_info,
forward_message,
forward_messages,
copy_message,
copy_messages,
send_message,
send_message_draft,
send_rich_message,
send_rich_message_draft,
send_photo,
send_live_photo,
send_audio,
send_document,
send_video,
send_animation,
send_voice,
send_video_note,
send_paid_media,
send_media_group,
send_location,
edit_message_live_location,
edit_message_live_location_inline,
stop_message_live_location,
stop_message_live_location_inline,
edit_message_checklist,
edit_ephemeral_message_text,
edit_ephemeral_message_caption,
edit_ephemeral_message_media,
edit_ephemeral_message_reply_markup,
send_venue,
send_contact,
send_poll,
send_checklist,
send_dice,
send_chat_action,
set_message_reaction,
get_user_profile_photos,
set_user_emoji_status,
get_file,
kick_chat_member,
ban_chat_member,
unban_chat_member,
restrict_chat_member,
promote_chat_member,
set_chat_administrator_custom_title,
set_chat_member_tag,
ban_chat_sender_chat,
unban_chat_sender_chat,
set_chat_permissions,
export_chat_invite_link,
create_chat_invite_link,
edit_chat_invite_link,
create_chat_subscription_invite_link,
edit_chat_subscription_invite_link,
revoke_chat_invite_link,
set_chat_photo,
delete_chat_photo,
set_chat_title,
set_chat_description,
pin_chat_message,
unpin_chat_message,
unpin_all_chat_messages,
leave_chat,
get_chat,
get_chat_administrators,
get_chat_members_count,
get_chat_member_count,
get_chat_member,
get_user_personal_chat_messages,
set_chat_sticker_set,
delete_chat_sticker_set,
get_forum_topic_icon_stickers,
create_forum_topic,
edit_forum_topic,
close_forum_topic,
reopen_forum_topic,
delete_forum_topic,
unpin_all_forum_topic_messages,
edit_general_forum_topic,
close_general_forum_topic,
reopen_general_forum_topic,
hide_general_forum_topic,
unhide_general_forum_topic,
unpin_all_general_forum_topic_messages,
answer_callback_query,
get_user_chat_boosts,
answer_guest_query,
set_my_commands,
get_business_connection,
get_my_commands,
get_my_name,
get_my_description,
get_my_short_description,
set_chat_menu_button,
get_chat_menu_button,
set_my_default_administrator_rights,
get_my_default_administrator_rights,
delete_my_commands,
answer_inline_query,
answer_web_app_query,
save_prepared_inline_message,
get_managed_bot_token,
get_managed_bot_access_settings,
set_managed_bot_access_settings,
replace_managed_bot_token,
save_prepared_keyboard_button,
edit_message_text,
edit_message_text_inline,
edit_message_caption,
edit_message_caption_inline,
edit_message_media,
edit_message_media_inline,
edit_message_reply_markup,
edit_message_reply_markup_inline,
stop_poll,
approve_suggested_post,
decline_suggested_post,
delete_message,
delete_ephemeral_message,
delete_messages,
delete_message_reaction,
delete_all_message_reactions,
send_sticker,
get_sticker_set,
get_custom_emoji_stickers,
upload_sticker_file,
create_new_sticker_set,
add_sticker_to_set,
set_sticker_position_in_set,
delete_sticker_from_set,
replace_sticker_in_set,
set_sticker_set_thumbnail,
set_custom_emoji_sticker_set_thumbnail,
set_sticker_set_title,
delete_sticker_set,
set_sticker_emoji_list,
set_sticker_keywords,
set_sticker_mask_position,
get_available_gifts,
send_gift,
send_gift_chat,
gift_premium_subscription,
verify_user,
verify_chat,
remove_user_verification,
remove_chat_verification,
read_business_message,
delete_business_messages,
set_business_account_name,
set_business_account_username,
set_business_account_bio,
set_business_account_profile_photo,
remove_business_account_profile_photo,
set_business_account_gift_settings,
get_business_account_star_balance,
transfer_business_account_stars,
get_business_account_gifts,
get_user_gifts,
get_user_profile_audios,
get_chat_gifts,
convert_gift_to_stars,
upgrade_gift,
transfer_gift,
repost_story,
post_story,
edit_story,
delete_story,
send_invoice,
create_invoice_link,
answer_shipping_query,
answer_pre_checkout_query,
get_my_star_balance,
get_star_transactions,
refund_star_payment,
edit_user_star_subscription,
set_passport_data_errors,
send_game,
set_game_score,
set_game_score_inline,
get_game_high_scores,
approve_chat_join_request,
decline_chat_join_request,
answer_chat_join_request_query,
send_chat_join_request_web_app
=> f, fty
}
}
download_forward! {
B
CacheMe<B>
{ this => this.inner() }
}
#[must_use = "Requests are lazy and do nothing unless sent"]
pub struct CachedMeRequest<R: Request<Payload = GetMe>>(R, Arc<MeCache>);
impl<R> Request for CachedMeRequest<R>
where
R: Request<Payload = GetMe>,
{
type Err = R::Err;
type Send = Send<R>;
type SendRef = SendRef<R>;
fn send(self) -> Self::Send {
let cell = self.1.current();
Send(match cell.get() {
Some(me) => future::Either::Left(ok(me.clone())),
None => future::Either::Right(Init(self.0.send(), cell)),
})
}
fn send_ref(&self) -> Self::SendRef {
let cell = self.1.current();
SendRef(match cell.get() {
Some(me) => future::Either::Left(ok(me.clone())),
None => future::Either::Right(Init(self.0.send_ref(), cell)),
})
}
}
impl<R: Request<Payload = GetMe>> HasPayload for CachedMeRequest<R> {
type Payload = GetMe;
fn payload_mut(&mut self) -> &mut Self::Payload {
self.0.payload_mut()
}
fn payload_ref(&self) -> &Self::Payload {
self.0.payload_ref()
}
}
impl<R: Request<Payload = GetMe>> IntoFuture for CachedMeRequest<R> {
type Output = Result<BotFullInfo, R::Err>;
type IntoFuture = Send<R>;
fn into_future(self) -> Self::IntoFuture {
self.send()
}
}
type ReadyMe<Err> = Ready<Result<BotFullInfo, Err>>;
#[pin_project::pin_project]
pub struct Send<R: Request<Payload = GetMe>>(
#[pin] future::Either<ReadyMe<R::Err>, Init<R::Send, BotFullInfo>>,
);
impl<R: Request<Payload = GetMe>> Future for Send<R> {
type Output = Result<BotFullInfo, R::Err>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
this.0.poll(cx)
}
}
#[pin_project::pin_project]
pub struct SendRef<R: Request<Payload = GetMe>>(
#[pin] future::Either<ReadyMe<R::Err>, Init<R::SendRef, BotFullInfo>>,
);
impl<R: Request<Payload = GetMe>> Future for SendRef<R> {
type Output = Result<BotFullInfo, R::Err>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
this.0.poll(cx)
}
}
#[pin_project::pin_project]
struct Init<F, T>(#[pin] F, Arc<OnceCell<T>>);
impl<F: Future<Output = Result<T, E>>, T: Clone, E> Future for Init<F, T> {
type Output = Result<T, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.0.poll(cx) {
Poll::Ready(Ok(ok)) => Poll::Ready(Ok(this.1.get_or_init(|| ok).clone())),
poll @ Poll::Ready(_) | poll @ Poll::Pending => poll,
}
}
}
#[derive(Clone)]
#[must_use = "Requests are lazy and do nothing unless sent"]
pub struct InvalidateMeRequest<R>(R, Arc<MeCache>);
impl<R: Request> Request for InvalidateMeRequest<R> {
type Err = R::Err;
type Send = InvalidateMe<R::Send>;
type SendRef = InvalidateMe<R::SendRef>;
fn send(self) -> Self::Send {
InvalidateMe(self.0.send(), self.1)
}
fn send_ref(&self) -> Self::SendRef {
InvalidateMe(self.0.send_ref(), Arc::clone(&self.1))
}
}
impl<R: Request> HasPayload for InvalidateMeRequest<R> {
type Payload = R::Payload;
fn payload_mut(&mut self) -> &mut Self::Payload {
self.0.payload_mut()
}
fn payload_ref(&self) -> &Self::Payload {
self.0.payload_ref()
}
}
impl<R: Request> IntoFuture for InvalidateMeRequest<R> {
type Output = Result<Output<R>, R::Err>;
type IntoFuture = InvalidateMe<R::Send>;
fn into_future(self) -> Self::IntoFuture {
self.send()
}
}
#[pin_project::pin_project]
pub struct InvalidateMe<F>(#[pin] F, Arc<MeCache>);
impl<F: Future<Output = Result<T, E>>, T, E> Future for InvalidateMe<F> {
type Output = Result<T, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let result = this.0.poll(cx);
if matches!(&result, Poll::Ready(Ok(_))) {
this.1.invalidate();
}
result
}
}
#[cfg(test)]
mod tests {
use std::{
io::{BufRead, BufReader, Write},
net::TcpListener,
time::Duration,
};
use serde_json::json;
use super::*;
use crate::{
payloads::{SetMyNameSetters, SetMySettingsSetters},
Bot,
};
fn bot_info(first_name: &str) -> serde_json::Value {
json!({
"id": 42, "is_bot": true, "first_name": first_name,
"can_join_groups": true, "can_read_all_group_messages": false,
"supports_guest_queries": false, "supports_inline_queries": false,
"needs_inline_query_location": false, "can_connect_to_business": false,
"has_main_web_app": false, "has_topics_enabled": false,
"allows_users_to_create_topics": false, "has_topic_sidebar": false,
"can_manage_bots": false, "supports_join_request_queries": false
})
}
#[tokio::test]
async fn successful_profile_writes_refresh_all_clones_but_errors_do_not() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
let server = std::thread::spawn(move || {
for (method, body) in [
("GetMe", json!({"ok": true, "result": bot_info("Old")})),
(
"SetMySettings",
json!({"ok": false, "error_code": 400, "description": "Bad Request: test"}),
),
("SetMyName", json!({"ok": true, "result": true})),
("GetMe", json!({"ok": true, "result": bot_info("New")})),
("SetMySettings", json!({"ok": true, "result": true})),
("GetMe", json!({"ok": true, "result": bot_info("Latest")})),
] {
let (mut stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let mut headers = BufReader::new(&mut stream);
let mut request_line = String::new();
headers.read_line(&mut request_line).unwrap();
assert!(
request_line
.to_ascii_lowercase()
.contains(&format!("/{} ", method.to_ascii_lowercase())),
"{request_line}"
);
loop {
let mut line = String::new();
if headers.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
break;
}
}
let body = body.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();
}
});
let mut cached = CacheMe::new(Bot::new("test-token").set_api_url(url));
let clone = cached.clone();
let get = clone.get_me();
let settings = cached.set_my_settings().can_join_groups(false);
tokio::time::timeout(Duration::from_secs(5), async {
assert_eq!(get.send_ref().await.unwrap().first_name, "Old");
assert!(settings.send_ref().await.is_err());
assert_eq!(get.send_ref().await.unwrap().first_name, "Old");
cached.set_my_name().name("New").await.unwrap();
assert_eq!(get.send_ref().await.unwrap().first_name, "New");
settings.send_ref().await.unwrap();
assert_eq!(get.await.unwrap().first_name, "Latest");
})
.await
.unwrap();
assert_eq!(cached.clear().unwrap().first_name, "Latest");
assert!(cached.clear().is_none());
assert_eq!(clone.get_me().await.unwrap().first_name, "Latest");
server.join().unwrap();
}
#[tokio::test]
async fn an_old_response_cannot_repopulate_the_new_cache() {
let cache = MeCache::default();
let old: BotFullInfo = serde_json::from_value(bot_info("Old")).unwrap();
let request = Init(ok::<_, std::convert::Infallible>(old), cache.current());
cache.invalidate();
assert_eq!(request.await.unwrap().first_name, "Old");
assert!(cache.current().get().is_none());
}
}