1use std::{
2 future::IntoFuture,
3 pin::Pin,
4 sync::{Arc, RwLock},
5};
6
7use futures::{
8 future,
9 future::{ok, Ready},
10 task::{Context, Poll},
11 Future,
12};
13use once_cell::sync::OnceCell;
14use url::Url;
15
16use crate::{
17 errors::AsResponseParameters,
18 payloads::GetMe,
19 requests::{HasPayload, Output, Request, Requester},
20 types::*,
21};
22
23#[derive(Clone, Debug)]
30pub struct CacheMe<B> {
31 bot: B,
32 me: Arc<MeCache>,
33}
34
35#[derive(Debug, Default)]
38struct MeCache(RwLock<Arc<OnceCell<BotFullInfo>>>);
39
40impl MeCache {
41 fn current(&self) -> Arc<OnceCell<BotFullInfo>> {
42 Arc::clone(&self.0.read().unwrap_or_else(|err| err.into_inner()))
43 }
44
45 fn invalidate(&self) {
46 *self.0.write().unwrap_or_else(|err| err.into_inner()) = Arc::default();
47 }
48}
49
50impl<B> CacheMe<B> {
51 pub fn new(bot: B) -> CacheMe<B> {
57 Self { bot, me: Arc::default() }
58 }
59
60 pub fn inner(&self) -> &B {
62 &self.bot
63 }
64
65 pub fn into_inner(self) -> B {
67 self.bot
68 }
69
70 pub fn clear(&mut self) -> Option<BotFullInfo> {
76 let previous = self.me.current().get().cloned();
77 self.me = Arc::default();
78 previous
79 }
80}
81
82macro_rules! f {
83 ($m:ident $this:ident ($($arg:ident : $T:ty),*)) => {
84 $this.inner().$m($($arg),*)
85 };
86}
87
88macro_rules! fty {
89 ($T:ident) => {
90 B::$T
91 };
92}
93
94impl<B> Requester for CacheMe<B>
95where
96 B: Requester,
97{
98 type Err = B::Err;
99
100 type GetMe = CachedMeRequest<B::GetMe>;
101
102 fn get_me(&self) -> Self::GetMe {
103 CachedMeRequest(self.bot.get_me(), Arc::clone(&self.me))
104 }
105
106 type SetMySettings = InvalidateMeRequest<B::SetMySettings>;
107
108 fn set_my_settings(&self) -> Self::SetMySettings {
109 InvalidateMeRequest(self.bot.set_my_settings(), Arc::clone(&self.me))
110 }
111
112 type SetMyName = InvalidateMeRequest<B::SetMyName>;
113
114 fn set_my_name(&self) -> Self::SetMyName {
115 InvalidateMeRequest(self.bot.set_my_name(), Arc::clone(&self.me))
116 }
117
118 type SetMyDescription = InvalidateMeRequest<B::SetMyDescription>;
119
120 fn set_my_description(&self) -> Self::SetMyDescription {
121 InvalidateMeRequest(self.bot.set_my_description(), Arc::clone(&self.me))
122 }
123
124 type SetMyShortDescription = InvalidateMeRequest<B::SetMyShortDescription>;
125
126 fn set_my_short_description(&self) -> Self::SetMyShortDescription {
127 InvalidateMeRequest(self.bot.set_my_short_description(), Arc::clone(&self.me))
128 }
129
130 type SetMyProfilePhoto = InvalidateMeRequest<B::SetMyProfilePhoto>;
131
132 fn set_my_profile_photo(&self, photo: InputProfilePhoto) -> Self::SetMyProfilePhoto {
133 InvalidateMeRequest(self.bot.set_my_profile_photo(photo), Arc::clone(&self.me))
134 }
135
136 type RemoveMyProfilePhoto = InvalidateMeRequest<B::RemoveMyProfilePhoto>;
137
138 fn remove_my_profile_photo(&self) -> Self::RemoveMyProfilePhoto {
139 InvalidateMeRequest(self.bot.remove_my_profile_photo(), Arc::clone(&self.me))
140 }
141
142 requester_forward! {
143 send_widget,
144 send_shared_widget,
145 get_chat_share_theme_backdrops,
146 answer_widget_query,
147 get_unique_gift,
148 delete_business_account_gift,
149 edit_message_widget_data,
150 edit_message_widget_data_inline,
151 edit_shared_widget_data,
152 log_out,
153 close,
154 get_updates,
155 set_webhook,
156 delete_webhook,
157 get_webhook_info,
158 forward_message,
159 forward_messages,
160 copy_message,
161 copy_messages,
162 send_message,
163 send_message_draft,
164 send_rich_message,
165 send_rich_message_draft,
166 send_photo,
167 send_live_photo,
168 send_audio,
169 send_document,
170 send_video,
171 send_animation,
172 send_voice,
173 send_video_note,
174 send_paid_media,
175 send_media_group,
176 send_location,
177 edit_message_live_location,
178 edit_message_live_location_inline,
179 stop_message_live_location,
180 stop_message_live_location_inline,
181 edit_message_checklist,
182 edit_ephemeral_message_text,
183 edit_ephemeral_message_caption,
184 edit_ephemeral_message_media,
185 edit_ephemeral_message_reply_markup,
186 send_venue,
187 send_contact,
188 send_poll,
189 send_checklist,
190 send_dice,
191 send_chat_action,
192 set_message_reaction,
193 get_user_profile_photos,
194 set_user_emoji_status,
195 get_file,
196 kick_chat_member,
197 ban_chat_member,
198 unban_chat_member,
199 restrict_chat_member,
200 promote_chat_member,
201 set_chat_administrator_custom_title,
202 set_chat_member_tag,
203 ban_chat_sender_chat,
204 unban_chat_sender_chat,
205 set_chat_permissions,
206 export_chat_invite_link,
207 create_chat_invite_link,
208 edit_chat_invite_link,
209 create_chat_subscription_invite_link,
210 edit_chat_subscription_invite_link,
211 revoke_chat_invite_link,
212 set_chat_photo,
213 delete_chat_photo,
214 set_chat_title,
215 set_chat_description,
216 pin_chat_message,
217 unpin_chat_message,
218 unpin_all_chat_messages,
219 leave_chat,
220 get_chat,
221 get_chat_administrators,
222 get_chat_members_count,
223 get_chat_member_count,
224 get_chat_member,
225 get_user_personal_chat_messages,
226 set_chat_sticker_set,
227 delete_chat_sticker_set,
228 get_forum_topic_icon_stickers,
229 create_forum_topic,
230 edit_forum_topic,
231 close_forum_topic,
232 reopen_forum_topic,
233 delete_forum_topic,
234 unpin_all_forum_topic_messages,
235 edit_general_forum_topic,
236 close_general_forum_topic,
237 reopen_general_forum_topic,
238 hide_general_forum_topic,
239 unhide_general_forum_topic,
240 unpin_all_general_forum_topic_messages,
241 answer_callback_query,
242 get_user_chat_boosts,
243 answer_guest_query,
244 set_my_commands,
245 get_business_connection,
246 get_my_commands,
247 get_my_name,
248 get_my_description,
249 get_my_short_description,
250 set_chat_menu_button,
251 get_chat_menu_button,
252 set_my_default_administrator_rights,
253 get_my_default_administrator_rights,
254 delete_my_commands,
255 answer_inline_query,
256 answer_web_app_query,
257 save_prepared_inline_message,
258 get_managed_bot_token,
259 get_managed_bot_access_settings,
260 set_managed_bot_access_settings,
261 replace_managed_bot_token,
262 save_prepared_keyboard_button,
263 edit_message_text,
264 edit_message_text_inline,
265 edit_message_caption,
266 edit_message_caption_inline,
267 edit_message_media,
268 edit_message_media_inline,
269 edit_message_reply_markup,
270 edit_message_reply_markup_inline,
271 stop_poll,
272 approve_suggested_post,
273 decline_suggested_post,
274 delete_message,
275 delete_ephemeral_message,
276 delete_messages,
277 delete_message_reaction,
278 delete_all_message_reactions,
279 send_sticker,
280 get_sticker_set,
281 get_custom_emoji_stickers,
282 upload_sticker_file,
283 create_new_sticker_set,
284 add_sticker_to_set,
285 set_sticker_position_in_set,
286 delete_sticker_from_set,
287 replace_sticker_in_set,
288 set_sticker_set_thumbnail,
289 set_custom_emoji_sticker_set_thumbnail,
290 set_sticker_set_title,
291 delete_sticker_set,
292 set_sticker_emoji_list,
293 set_sticker_keywords,
294 set_sticker_mask_position,
295 get_available_gifts,
296 send_gift,
297 send_gift_chat,
298 gift_premium_subscription,
299 verify_user,
300 verify_chat,
301 remove_user_verification,
302 remove_chat_verification,
303 read_business_message,
304 delete_business_messages,
305 set_business_account_name,
306 set_business_account_username,
307 set_business_account_bio,
308 set_business_account_profile_photo,
309 remove_business_account_profile_photo,
310 set_business_account_gift_settings,
311 get_business_account_star_balance,
312 transfer_business_account_stars,
313 get_business_account_gifts,
314 get_user_gifts,
315 get_user_profile_audios,
316 get_chat_gifts,
317 convert_gift_to_stars,
318 upgrade_gift,
319 transfer_gift,
320 repost_story,
321 post_story,
322 edit_story,
323 delete_story,
324 send_invoice,
325 create_invoice_link,
326 answer_shipping_query,
327 answer_pre_checkout_query,
328 get_my_star_balance,
329 get_star_transactions,
330 refund_star_payment,
331 edit_user_star_subscription,
332 set_passport_data_errors,
333 send_game,
334 set_game_score,
335 set_game_score_inline,
336 get_game_high_scores,
337 approve_chat_join_request,
338 decline_chat_join_request,
339 answer_chat_join_request_query,
340 send_chat_join_request_web_app
341 => f, fty
342 }
343}
344
345download_forward! {
346 B
347 CacheMe<B>
348 { this => this.inner() }
349}
350
351#[must_use = "Requests are lazy and do nothing unless sent"]
352pub struct CachedMeRequest<R: Request<Payload = GetMe>>(R, Arc<MeCache>);
353
354impl<R> Request for CachedMeRequest<R>
355where
356 R: Request<Payload = GetMe>,
357{
358 type Err = R::Err;
359 type Send = Send<R>;
360 type SendRef = SendRef<R>;
361
362 fn send(self) -> Self::Send {
363 let cell = self.1.current();
364 Send(match cell.get() {
365 Some(me) => future::Either::Left(ok(me.clone())),
366 None => future::Either::Right(Init(self.0.send(), cell)),
367 })
368 }
369
370 fn send_ref(&self) -> Self::SendRef {
371 let cell = self.1.current();
372 SendRef(match cell.get() {
373 Some(me) => future::Either::Left(ok(me.clone())),
374 None => future::Either::Right(Init(self.0.send_ref(), cell)),
375 })
376 }
377}
378
379impl<R: Request<Payload = GetMe>> HasPayload for CachedMeRequest<R> {
380 type Payload = GetMe;
381
382 fn payload_mut(&mut self) -> &mut Self::Payload {
383 self.0.payload_mut()
384 }
385
386 fn payload_ref(&self) -> &Self::Payload {
387 self.0.payload_ref()
388 }
389}
390
391impl<R: Request<Payload = GetMe>> IntoFuture for CachedMeRequest<R> {
392 type Output = Result<BotFullInfo, R::Err>;
393 type IntoFuture = Send<R>;
394
395 fn into_future(self) -> Self::IntoFuture {
396 self.send()
397 }
398}
399
400type ReadyMe<Err> = Ready<Result<BotFullInfo, Err>>;
401
402#[pin_project::pin_project]
403pub struct Send<R: Request<Payload = GetMe>>(
404 #[pin] future::Either<ReadyMe<R::Err>, Init<R::Send, BotFullInfo>>,
405);
406
407impl<R: Request<Payload = GetMe>> Future for Send<R> {
408 type Output = Result<BotFullInfo, R::Err>;
409
410 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
411 let this = self.project();
412 this.0.poll(cx)
413 }
414}
415
416#[pin_project::pin_project]
417pub struct SendRef<R: Request<Payload = GetMe>>(
418 #[pin] future::Either<ReadyMe<R::Err>, Init<R::SendRef, BotFullInfo>>,
419);
420
421impl<R: Request<Payload = GetMe>> Future for SendRef<R> {
422 type Output = Result<BotFullInfo, R::Err>;
423
424 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
425 let this = self.project();
426 this.0.poll(cx)
427 }
428}
429
430#[pin_project::pin_project]
431struct Init<F, T>(#[pin] F, Arc<OnceCell<T>>);
432
433impl<F: Future<Output = Result<T, E>>, T: Clone, E> Future for Init<F, T> {
434 type Output = Result<T, E>;
435
436 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
437 let this = self.project();
438 match this.0.poll(cx) {
439 Poll::Ready(Ok(ok)) => Poll::Ready(Ok(this.1.get_or_init(|| ok).clone())),
440 poll @ Poll::Ready(_) | poll @ Poll::Pending => poll,
441 }
442 }
443}
444
445#[derive(Clone)]
448#[must_use = "Requests are lazy and do nothing unless sent"]
449pub struct InvalidateMeRequest<R>(R, Arc<MeCache>);
450
451impl<R: Request<Err: AsResponseParameters>> Request for InvalidateMeRequest<R> {
452 type Err = R::Err;
453 type Send = InvalidateMe<R::Send>;
454 type SendRef = InvalidateMe<R::SendRef>;
455
456 fn send(self) -> Self::Send {
457 InvalidateMe(self.0.send(), self.1, false)
458 }
459
460 fn send_ref(&self) -> Self::SendRef {
461 InvalidateMe(self.0.send_ref(), Arc::clone(&self.1), false)
462 }
463}
464
465impl<R: Request> HasPayload for InvalidateMeRequest<R> {
466 type Payload = R::Payload;
467
468 fn payload_mut(&mut self) -> &mut Self::Payload {
469 self.0.payload_mut()
470 }
471
472 fn payload_ref(&self) -> &Self::Payload {
473 self.0.payload_ref()
474 }
475}
476
477impl<R: Request<Err: AsResponseParameters>> IntoFuture for InvalidateMeRequest<R> {
478 type Output = Result<Output<R>, R::Err>;
479 type IntoFuture = InvalidateMe<R::Send>;
480
481 fn into_future(self) -> Self::IntoFuture {
482 self.send()
483 }
484}
485
486#[pin_project::pin_project(PinnedDrop)]
489pub struct InvalidateMe<F>(#[pin] F, Arc<MeCache>, bool);
490
491impl<F: Future<Output = Result<T, E>>, T, E: AsResponseParameters> Future for InvalidateMe<F> {
492 type Output = Result<T, E>;
493
494 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
495 let this = self.project();
496 *this.2 = true;
497 let result = this.0.poll(cx);
498 if let Poll::Ready(result) = &result {
499 *this.2 = false;
500 if !result.as_ref().is_err_and(AsResponseParameters::is_api_refusal) {
501 this.1.invalidate();
502 }
503 }
504 result
505 }
506}
507
508#[pin_project::pinned_drop]
509impl<F> PinnedDrop for InvalidateMe<F> {
510 fn drop(self: Pin<&mut Self>) {
511 let this = self.project();
512 if *this.2 {
513 this.1.invalidate();
514 }
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use std::{
521 io::{BufRead, BufReader, Write},
522 net::TcpListener,
523 time::Duration,
524 };
525
526 use serde_json::json;
527
528 use super::*;
529 use crate::{
530 payloads::{SetMyNameSetters, SetMySettingsSetters},
531 Bot,
532 };
533
534 fn bot_info(first_name: &str) -> serde_json::Value {
535 json!({
536 "id": 42, "is_bot": true, "first_name": first_name,
537 "can_join_groups": true, "can_read_all_group_messages": false,
538 "supports_guest_queries": false, "supports_inline_queries": false,
539 "needs_inline_query_location": false, "can_connect_to_business": false,
540 "has_main_web_app": false, "has_topics_enabled": false,
541 "allows_users_to_create_topics": false, "has_topic_sidebar": false,
542 "can_manage_bots": false, "supports_join_request_queries": false
543 })
544 }
545
546 #[tokio::test]
547 async fn successful_profile_writes_refresh_all_clones_but_errors_do_not() {
548 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
549 let url = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
550 let server = std::thread::spawn(move || {
551 for (method, body) in [
552 ("GetMe", json!({"ok": true, "result": bot_info("Old")})),
553 (
554 "SetMySettings",
555 json!({"ok": false, "error_code": 400, "description": "Bad Request: test"}),
556 ),
557 ("SetMyName", json!({"ok": true, "result": true})),
558 ("GetMe", json!({"ok": true, "result": bot_info("New")})),
559 ("SetMySettings", json!({"ok": true, "result": true})),
560 ("GetMe", json!({"ok": true, "result": bot_info("Latest")})),
561 ] {
562 let (mut stream, _) = listener.accept().unwrap();
563 stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
564 let mut headers = BufReader::new(&mut stream);
565 let mut request_line = String::new();
566 headers.read_line(&mut request_line).unwrap();
567 assert!(
568 request_line
569 .to_ascii_lowercase()
570 .contains(&format!("/{} ", method.to_ascii_lowercase())),
571 "{request_line}"
572 );
573 loop {
574 let mut line = String::new();
575 if headers.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
576 break;
577 }
578 }
579 let body = body.to_string();
580 write!(
581 stream,
582 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: \
583 {}\r\nConnection: close\r\n\r\n{body}",
584 body.len()
585 )
586 .unwrap();
587 }
588 });
589 let mut cached = CacheMe::new(Bot::new("test-token").set_api_url(url));
590 let clone = cached.clone();
591 let get = clone.get_me();
592 let settings = cached.set_my_settings().can_join_groups(false);
593 tokio::time::timeout(Duration::from_secs(5), async {
594 assert_eq!(get.send_ref().await.unwrap().first_name, "Old");
595 assert!(settings.send_ref().await.is_err());
596 assert_eq!(get.send_ref().await.unwrap().first_name, "Old");
597 cached.set_my_name().name("New").await.unwrap();
598 assert_eq!(get.send_ref().await.unwrap().first_name, "New");
599 settings.send_ref().await.unwrap();
600 assert_eq!(get.await.unwrap().first_name, "Latest");
601 })
602 .await
603 .unwrap();
604 assert_eq!(cached.clear().unwrap().first_name, "Latest");
605 assert!(cached.clear().is_none());
606 assert_eq!(clone.get_me().await.unwrap().first_name, "Latest");
607 server.join().unwrap();
608 }
609
610 #[tokio::test]
611 async fn uncertain_mutation_outcomes_discard_the_current_generation() {
612 use crate::RequestError;
613 let cache = Arc::new(MeCache::default());
614 let current = cache.current();
615 let mut pending = Box::pin(InvalidateMe(
616 future::pending::<Result<(), RequestError>>(),
617 Arc::clone(&cache),
618 false,
619 ));
620 assert!(futures::poll!(&mut pending).is_pending());
621 drop(pending);
622 assert!(!Arc::ptr_eq(¤t, &cache.current()));
623
624 let current = cache.current();
625 let uncertain = RequestError::Io(Arc::new(std::io::Error::other("lost response")));
626 assert!(InvalidateMe(future::err::<(), _>(uncertain), Arc::clone(&cache), false)
627 .await
628 .is_err());
629 assert!(!Arc::ptr_eq(¤t, &cache.current()));
630 }
631
632 #[tokio::test]
633 async fn an_old_response_cannot_repopulate_the_new_cache() {
634 let cache = MeCache::default();
635 let old: BotFullInfo = serde_json::from_value(bot_info("Old")).unwrap();
636 let request = Init(ok::<_, std::convert::Infallible>(old), cache.current());
637 cache.invalidate();
638 assert_eq!(request.await.unwrap().first_name, "Old");
639 assert!(cache.current().get().is_none());
640 }
641}