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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! A cache containing data received from [`Shard`]s.
//!
//! Using the cache allows to avoid REST API requests via the [`http`] module where possible.
//! Issuing too many requests will lead to ratelimits.
//!
//! # Use by Models
//!
//! Most models of Discord objects, such as the [`Message`], [`GuildChannel`], or [`Emoji`], have
//! methods for interacting with that single instance. This feature is only compiled if the `model`
//! feature is enabled. An example of this is [`Guild::edit`], which performs a check to ensure that
//! the current user has the [Manage Guild] permission prior to actually performing the HTTP
//! request. The cache is involved due to the function's use of unlocking the cache and retrieving
//! the permissions of the current user. This is an inexpensive method of being able to access data
//! required by these sugary methods.
//!
//! # Do I need the Cache?
//!
//! If you're asking this, the answer is likely "definitely yes" or "definitely no"; any in-between
//! tends to be "yes". If you are low on RAM, and need to run on only a couple MB, then the answer
//! is "definitely no". If you do not care about RAM and want your bot to be able to access data
//! while needing to hit the REST API as little as possible, then the answer is "yes".
//!
//! [`Shard`]: crate::gateway::Shard
//! [`http`]: crate::http
//! [Manage Guild]: Permissions::MANAGE_GUILD

use std::collections::{HashSet, VecDeque};
use std::hash::Hash;
#[cfg(feature = "temp_cache")]
use std::sync::Arc;
#[cfg(feature = "temp_cache")]
use std::time::Duration;

use dashmap::mapref::entry::Entry;
use dashmap::mapref::one::{MappedRef, Ref};
use dashmap::DashMap;
#[cfg(feature = "temp_cache")]
use mini_moka::sync::Cache as MokaCache;
use parking_lot::RwLock;
use tracing::instrument;

pub use self::cache_update::CacheUpdate;
pub use self::settings::Settings;
use crate::model::prelude::*;

mod cache_update;
mod event;
mod settings;
mod wrappers;

#[cfg(feature = "temp_cache")]
pub(crate) use wrappers::MaybeOwnedArc;
use wrappers::{BuildHasher, MaybeMap, ReadOnlyMapRef};

type MessageCache = DashMap<ChannelId, HashMap<MessageId, Message>, BuildHasher>;

struct NotSend;

enum CacheRefInner<'a, K, V, T> {
    #[cfg(feature = "temp_cache")]
    Arc(Arc<V>),
    DashRef(Ref<'a, K, V, BuildHasher>),
    DashMappedRef(MappedRef<'a, K, T, V, BuildHasher>),
    ReadGuard(parking_lot::RwLockReadGuard<'a, V>),
}

pub struct CacheRef<'a, K, V, T = ()> {
    inner: CacheRefInner<'a, K, V, T>,
    phantom: std::marker::PhantomData<*const NotSend>,
}

impl<'a, K, V, T> CacheRef<'a, K, V, T> {
    fn new(inner: CacheRefInner<'a, K, V, T>) -> Self {
        Self {
            inner,
            phantom: std::marker::PhantomData,
        }
    }

    #[cfg(feature = "temp_cache")]
    fn from_arc(inner: MaybeOwnedArc<V>) -> Self {
        Self::new(CacheRefInner::Arc(inner.get_inner()))
    }

    fn from_ref(inner: Ref<'a, K, V, BuildHasher>) -> Self {
        Self::new(CacheRefInner::DashRef(inner))
    }

    fn from_mapped_ref(inner: MappedRef<'a, K, T, V, BuildHasher>) -> Self {
        Self::new(CacheRefInner::DashMappedRef(inner))
    }

    fn from_guard(inner: parking_lot::RwLockReadGuard<'a, V>) -> Self {
        Self::new(CacheRefInner::ReadGuard(inner))
    }
}

impl<K: Eq + Hash, V, T> std::ops::Deref for CacheRef<'_, K, V, T> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        match &self.inner {
            #[cfg(feature = "temp_cache")]
            CacheRefInner::Arc(inner) => inner,
            CacheRefInner::DashRef(inner) => inner.value(),
            CacheRefInner::DashMappedRef(inner) => inner.value(),
            CacheRefInner::ReadGuard(inner) => inner,
        }
    }
}

type MappedGuildRef<'a, T> = CacheRef<'a, GuildId, T, Guild>;

pub type UserRef<'a> = CacheRef<'a, UserId, User>;
pub type MemberRef<'a> = MappedGuildRef<'a, Member>;
pub type GuildRef<'a> = CacheRef<'a, GuildId, Guild>;
pub type GuildRoleRef<'a> = MappedGuildRef<'a, Role>;
pub type SettingsRef<'a> = CacheRef<'a, (), Settings>;
pub type CurrentUserRef<'a> = CacheRef<'a, (), CurrentUser>;
pub type GuildChannelRef<'a> = MappedGuildRef<'a, GuildChannel>;
pub type GuildRolesRef<'a> = MappedGuildRef<'a, HashMap<RoleId, Role>>;
pub type GuildChannelsRef<'a> = MappedGuildRef<'a, HashMap<ChannelId, GuildChannel>>;
pub type ChannelMessagesRef<'a> = CacheRef<'a, ChannelId, HashMap<MessageId, Message>>;
pub type MessageRef<'a> = CacheRef<'a, ChannelId, Message, HashMap<MessageId, Message>>;

#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Debug)]
pub(crate) struct CachedShardData {
    pub total: u32,
    pub connected: HashSet<ShardId>,
    pub has_sent_shards_ready: bool,
}

/// A cache containing data received from [`Shard`]s.
///
/// Using the cache allows to avoid REST API requests via the [`http`] module where possible.
/// Issuing too many requests will lead to ratelimits.
///
/// This is the list of cached resources and the events that populate them:
/// - channels: [`ChannelCreateEvent`], [`ChannelUpdateEvent`], [`GuildCreateEvent`]
/// - guilds: [`GuildCreateEvent`]
/// - unavailable_guilds: [`ReadyEvent`], [`GuildDeleteEvent`]
/// - users: [`GuildMemberAddEvent`], [`GuildMemberRemoveEvent`], [`GuildMembersChunkEvent`],
///   [`PresenceUpdateEvent`], [`ReadyEvent`]
/// - presences: [`PresenceUpdateEvent`], [`ReadyEvent`]
/// - messages: [`MessageCreateEvent`]
///
/// The documentation of each event contains the required gateway intents.
///
/// [`Shard`]: crate::gateway::Shard
/// [`http`]: crate::http
#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Debug)]
#[non_exhaustive]
pub struct Cache {
    // Temp cache:
    // ---
    /// Cache of channels that have been fetched via to_channel.
    ///
    /// The TTL for each value is configured in CacheSettings.
    #[cfg(feature = "temp_cache")]
    pub(crate) temp_channels: MokaCache<ChannelId, MaybeOwnedArc<GuildChannel>, BuildHasher>,
    /// Cache of private channels created via create_dm_channel.
    ///
    /// The TTL for each value is configured in CacheSettings.
    #[cfg(feature = "temp_cache")]
    pub(crate) temp_private_channels: MokaCache<UserId, MaybeOwnedArc<PrivateChannel>, BuildHasher>,
    /// Cache of messages that have been fetched via message.
    ///
    /// The TTL for each value is configured in CacheSettings.
    #[cfg(feature = "temp_cache")]
    pub(crate) temp_messages: MokaCache<MessageId, MaybeOwnedArc<Message>, BuildHasher>,
    /// Cache of users who have been fetched from `to_user`.
    ///
    /// The TTL for each value is configured in CacheSettings.
    #[cfg(feature = "temp_cache")]
    pub(crate) temp_users: MokaCache<UserId, MaybeOwnedArc<User>, BuildHasher>,

    // Channels cache:
    /// A map of channel ids to the guilds in which the channel data is stored.
    pub(crate) channels: MaybeMap<ChannelId, GuildId>,

    // Guilds cache:
    // ---
    /// A map of guilds with full data available. This includes data like [`Role`]s and [`Emoji`]s
    /// that are not available through the REST API.
    pub(crate) guilds: MaybeMap<GuildId, Guild>,
    /// A list of guilds which are "unavailable".
    ///
    /// Additionally, guilds are always unavailable for bot users when a Ready is received. Guilds
    /// are "sent in" over time through the receiving of [`Event::GuildCreate`]s.
    pub(crate) unavailable_guilds: MaybeMap<GuildId, ()>,

    // Users cache:
    // ---
    /// A map of users that the current user sees.
    ///
    /// Users are added to - and updated from - this map via the following received events:
    ///
    /// - [`GuildMemberAdd`][`GuildMemberAddEvent`]
    /// - [`GuildMemberRemove`][`GuildMemberRemoveEvent`]
    /// - [`GuildMembersChunk`][`GuildMembersChunkEvent`]
    /// - [`PresenceUpdate`][`PresenceUpdateEvent`]
    /// - [`Ready`][`ReadyEvent`]
    ///
    /// Note, however, that users are _not_ removed from the map on removal events such as
    /// [`GuildMemberRemove`][`GuildMemberRemoveEvent`], as other structs such as members or
    /// recipients may still exist.
    pub(crate) users: MaybeMap<UserId, User>,

    // Messages cache:
    // ---
    pub(crate) messages: MessageCache,
    /// Queue of message IDs for each channel.
    ///
    /// This is simply a vecdeque so we can keep track of the order of messages inserted into the
    /// cache. When a maximum number of messages are in a channel's cache, we can pop the front and
    /// remove that ID from the cache.
    pub(crate) message_queue: DashMap<ChannelId, VecDeque<MessageId>, BuildHasher>,

    // Miscellanous fixed-size data
    // ---
    /// Information about running shards
    pub(crate) shard_data: RwLock<CachedShardData>,
    /// The current user "logged in" and for which events are being received for.
    ///
    /// The current user contains information that a regular [`User`] does not, such as whether it
    /// is a bot, whether the user is verified, etc.
    ///
    /// Refer to the documentation for [`CurrentUser`] for more information.
    pub(crate) user: RwLock<CurrentUser>,
    /// The settings for the cache.
    settings: RwLock<Settings>,
}

impl Cache {
    /// Creates a new cache.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new cache instance with settings applied.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use serenity::cache::{Cache, Settings};
    ///
    /// let mut settings = Settings::default();
    /// settings.max_messages = 10;
    ///
    /// let cache = Cache::new_with_settings(settings);
    /// ```
    #[instrument]
    pub fn new_with_settings(settings: Settings) -> Self {
        #[cfg(feature = "temp_cache")]
        fn temp_cache<K, V>(ttl: Duration) -> MokaCache<K, V, BuildHasher>
        where
            K: Hash + Eq + Send + Sync + 'static,
            V: Clone + Send + Sync + 'static,
        {
            MokaCache::builder().time_to_live(ttl).build_with_hasher(BuildHasher::default())
        }

        Self {
            #[cfg(feature = "temp_cache")]
            temp_private_channels: temp_cache(settings.time_to_live),
            #[cfg(feature = "temp_cache")]
            temp_channels: temp_cache(settings.time_to_live),
            #[cfg(feature = "temp_cache")]
            temp_messages: temp_cache(settings.time_to_live),
            #[cfg(feature = "temp_cache")]
            temp_users: temp_cache(settings.time_to_live),

            channels: MaybeMap(settings.cache_channels.then(DashMap::default)),

            guilds: MaybeMap(settings.cache_guilds.then(DashMap::default)),
            unavailable_guilds: MaybeMap(settings.cache_guilds.then(DashMap::default)),

            users: MaybeMap(settings.cache_users.then(DashMap::default)),

            messages: DashMap::default(),
            message_queue: DashMap::default(),

            shard_data: RwLock::new(CachedShardData {
                total: 1,
                connected: HashSet::new(),
                has_sent_shards_ready: false,
            }),
            user: RwLock::new(CurrentUser::default()),
            settings: RwLock::new(settings),
        }
    }

    /// Fetches the number of [`Member`]s that have not had data received.
    ///
    /// The important detail to note here is that this is the number of _member_s that have not had
    /// data received. A single [`User`] may have multiple associated member objects that have not
    /// been received.
    ///
    /// This can be used in combination with [`Shard::chunk_guild`], and can be used to determine
    /// how many members have not yet been received.
    ///
    /// ```rust,no_run
    /// # use serenity::model::prelude::*;
    /// # use serenity::prelude::*;
    /// struct Handler;
    ///
    /// #[serenity::async_trait]
    /// # #[cfg(feature = "client")]
    /// impl EventHandler for Handler {
    ///     async fn cache_ready(&self, ctx: Context, _: Vec<GuildId>) {
    ///         println!("{} unknown members", ctx.cache.unknown_members());
    ///     }
    /// }
    /// ```
    ///
    /// [`Shard::chunk_guild`]: crate::gateway::Shard::chunk_guild
    pub fn unknown_members(&self) -> u64 {
        let mut total = 0;

        for guild_entry in self.guilds.iter() {
            let guild = guild_entry.value();

            let members = guild.members.len() as u64;

            if guild.member_count > members {
                total += guild.member_count - members;
            }
        }

        total
    }

    /// Fetches a vector of all [`Guild`]s' Ids that are stored in the cache.
    ///
    /// Note that if you are utilizing multiple [`Shard`]s, then the guilds retrieved over all
    /// shards are included in this count -- not just the current [`Context`]'s shard, if accessing
    /// from one.
    ///
    /// # Examples
    ///
    /// Print all of the Ids of guilds in the Cache:
    ///
    /// ```rust,no_run
    /// # use serenity::model::prelude::*;
    /// # use serenity::prelude::*;
    /// #
    /// struct Handler;
    ///
    /// #[serenity::async_trait]
    /// impl EventHandler for Handler {
    ///     async fn ready(&self, context: Context, _: Ready) {
    ///         let guilds = context.cache.guilds().len();
    ///
    ///         println!("Guilds in the Cache: {}", guilds);
    ///     }
    /// }
    /// ```
    ///
    /// [`Context`]: crate::client::Context
    /// [`Shard`]: crate::gateway::Shard
    pub fn guilds(&self) -> Vec<GuildId> {
        let unavailable_guilds = self.unavailable_guilds();

        let unavailable_guild_ids = unavailable_guilds.iter().map(|i| *i.key());

        self.guilds.iter().map(|i| *i.key()).chain(unavailable_guild_ids).collect()
    }

    /// Retrieves a [`GuildChannel`] from the cache based on the given Id.
    #[inline]
    #[deprecated = "Use Cache::guild and Guild::channels instead"]
    pub fn channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannelRef<'_>> {
        self._channel(id.into())
    }

    fn _channel(&self, id: ChannelId) -> Option<GuildChannelRef<'_>> {
        let guild_id = *self.channels.get(&id)?;
        let guild_ref = self.guilds.get(&guild_id)?;
        let channel = guild_ref.try_map(|g| g.channels.get(&id)).ok();
        if let Some(channel) = channel {
            return Some(CacheRef::from_mapped_ref(channel));
        }

        #[cfg(feature = "temp_cache")]
        {
            if let Some(channel) = self.temp_channels.get(&id) {
                return Some(CacheRef::from_arc(channel));
            }
        }

        None
    }

    /// Get a reference to the cached messages for a channel based on the given `Id`.
    ///
    /// # Examples
    ///
    /// Find all messages by user ID 8 in channel ID 7:
    ///
    /// ```rust,no_run
    /// # let cache: serenity::cache::Cache = todo!();
    /// let messages_in_channel = cache.channel_messages(7);
    /// let messages_by_user = messages_in_channel
    ///     .as_ref()
    ///     .map(|msgs| msgs.values().filter(|m| m.author.id == 8).collect::<Vec<_>>());
    /// ```
    pub fn channel_messages(
        &self,
        channel_id: impl Into<ChannelId>,
    ) -> Option<ChannelMessagesRef<'_>> {
        self.messages.get(&channel_id.into()).map(CacheRef::from_ref)
    }

    /// Gets a reference to a guild from the cache based on the given `id`.
    ///
    /// # Examples
    ///
    /// Retrieve a guild from the cache and print its name:
    ///
    /// ```rust,no_run
    /// # use serenity::cache::Cache;
    /// #
    /// # let cache = Cache::default();
    /// // assuming the cache is in scope, e.g. via `Context`
    /// if let Some(guild) = cache.guild(7) {
    ///     println!("Guild name: {}", guild.name);
    /// };
    /// ```
    #[inline]
    pub fn guild<G: Into<GuildId>>(&self, id: G) -> Option<GuildRef<'_>> {
        self._guild(id.into())
    }

    fn _guild(&self, id: GuildId) -> Option<GuildRef<'_>> {
        self.guilds.get(&id).map(CacheRef::from_ref)
    }

    /// Returns the number of cached guilds.
    pub fn guild_count(&self) -> usize {
        self.guilds.len()
    }

    /// Retrieves a [`Guild`]'s member from the cache based on the guild's and user's given Ids.
    ///
    /// # Examples
    ///
    /// Retrieving the member object of the user that posted a message, in a
    /// [`EventHandler::message`] context:
    ///
    /// ```rust,no_run
    /// # use serenity::cache::Cache;
    /// # use serenity::http::Http;
    /// # use serenity::model::channel::Message;
    /// #
    /// # async fn run(http: Http, cache: Cache, message: Message) {
    /// #
    /// let roles_len = {
    ///     let channel = match cache.channel(message.channel_id) {
    ///         Some(channel) => channel,
    ///         None => {
    ///             if let Err(why) = message.channel_id.say(http, "Error finding channel data").await {
    ///                 println!("Error sending message: {:?}", why);
    ///             }
    ///             return;
    ///         },
    ///     };
    ///
    ///     cache.member(channel.guild_id, message.author.id).map(|m| m.roles.len())
    /// };
    ///
    /// let message_res = if let Some(roles_len) = roles_len {
    ///     let msg = format!("You have {} roles", roles_len);
    ///     message.channel_id.say(&http, &msg).await
    /// } else {
    ///     message.channel_id.say(&http, "Error finding member data").await
    /// };
    ///
    /// if let Err(why) = message_res {
    ///     println!("Error sending message: {:?}", why);
    /// }
    /// # }
    /// ```
    ///
    /// [`EventHandler::message`]: crate::client::EventHandler::message
    /// [`members`]: crate::model::guild::Guild::members
    #[inline]
    #[deprecated = "Use Cache::guild and Guild::members instead"]
    pub fn member(
        &self,
        guild_id: impl Into<GuildId>,
        user_id: impl Into<UserId>,
    ) -> Option<MemberRef<'_>> {
        self._member(guild_id.into(), user_id.into())
    }

    fn _member(&self, guild_id: GuildId, user_id: UserId) -> Option<MemberRef<'_>> {
        let member = self.guilds.get(&guild_id)?.try_map(|g| g.members.get(&user_id)).ok()?;
        Some(CacheRef::from_mapped_ref(member))
    }

    #[inline]
    #[deprecated = "Use Cache::guild and Guild::roles instead"]
    pub fn guild_roles(&self, guild_id: impl Into<GuildId>) -> Option<GuildRolesRef<'_>> {
        self._guild_roles(guild_id.into())
    }

    fn _guild_roles(&self, guild_id: GuildId) -> Option<GuildRolesRef<'_>> {
        let roles = self.guilds.get(&guild_id)?.map(|g| &g.roles);
        Some(CacheRef::from_mapped_ref(roles))
    }

    /// This method clones and returns all unavailable guilds.
    #[inline]
    pub fn unavailable_guilds(&self) -> ReadOnlyMapRef<'_, GuildId, ()> {
        self.unavailable_guilds.as_read_only()
    }

    /// This method returns all channels from a guild of with the given `guild_id`.
    #[inline]
    #[deprecated = "Use Cache::guild and Guild::channels instead"]
    pub fn guild_channels(&self, guild_id: impl Into<GuildId>) -> Option<GuildChannelsRef<'_>> {
        self._guild_channels(guild_id.into())
    }

    fn _guild_channels(&self, guild_id: GuildId) -> Option<GuildChannelsRef<'_>> {
        let channels = self.guilds.get(&guild_id)?.map(|g| &g.channels);
        Some(CacheRef::from_mapped_ref(channels))
    }

    /// Returns the number of guild channels in the cache.
    pub fn guild_channel_count(&self) -> usize {
        self.channels.len()
    }

    /// Returns the number of shards.
    #[inline]
    pub fn shard_count(&self) -> u32 {
        self.shard_data.read().total
    }

    /// Retrieves a [`Channel`]'s message from the cache based on the channel's and message's given
    /// Ids.
    ///
    /// **Note**: This will clone the entire message.
    ///
    /// # Examples
    ///
    /// Retrieving the message object from a channel, in a [`EventHandler::message`] context:
    ///
    /// ```rust,no_run
    /// # use serenity::cache::Cache;
    /// # use serenity::model::channel::Message;
    /// #
    /// # fn run(cache: Cache, message: Message) {
    /// #
    /// match cache.message(message.channel_id, message.id) {
    ///     Some(m) => assert_eq!(message.content, m.content),
    ///     None => println!("No message found in cache."),
    /// };
    /// # }
    /// ```
    ///
    /// [`EventHandler::message`]: crate::client::EventHandler::message
    #[inline]
    pub fn message<C, M>(&self, channel_id: C, message_id: M) -> Option<MessageRef<'_>>
    where
        C: Into<ChannelId>,
        M: Into<MessageId>,
    {
        self._message(channel_id.into(), message_id.into())
    }

    fn _message(&self, channel_id: ChannelId, message_id: MessageId) -> Option<MessageRef<'_>> {
        #[cfg(feature = "temp_cache")]
        if let Some(message) = self.temp_messages.get(&message_id) {
            return Some(CacheRef::from_arc(message));
        }

        let channel_messages = self.messages.get(&channel_id)?;
        let message = channel_messages.try_map(|messages| messages.get(&message_id)).ok()?;
        Some(CacheRef::from_mapped_ref(message))
    }

    /// Retrieves a [`Guild`]'s role by their Ids.
    ///
    /// **Note**: This will clone the entire role. Instead, retrieve the guild and retrieve from
    /// the guild's [`roles`] map to avoid this.
    ///
    /// # Examples
    ///
    /// Retrieve a role from the cache and print its name:
    ///
    /// ```rust,no_run
    /// # use serenity::cache::Cache;
    /// #
    /// # let cache = Cache::default();
    /// // assuming the cache is in scope, e.g. via `Context`
    /// if let Some(role) = cache.role(7, 77) {
    ///     println!("Role with Id 77 is called {}", role.name);
    /// };
    /// ```
    ///
    /// [`Guild`]: crate::model::guild::Guild
    /// [`roles`]: crate::model::guild::Guild::roles
    #[inline]
    #[deprecated = "Use Cache::guild and Guild::roles instead"]
    pub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<GuildRoleRef<'_>>
    where
        G: Into<GuildId>,
        R: Into<RoleId>,
    {
        self._role(guild_id.into(), role_id.into())
    }

    fn _role(&self, guild_id: GuildId, role_id: RoleId) -> Option<GuildRoleRef<'_>> {
        let role = self.guilds.get(&guild_id)?.try_map(|g| g.roles.get(&role_id)).ok()?;
        Some(CacheRef::from_mapped_ref(role))
    }

    /// Returns the settings.
    ///
    /// # Examples
    ///
    /// Printing the maximum number of messages in a channel to be cached:
    ///
    /// ```rust
    /// use serenity::cache::Cache;
    ///
    /// # fn test() {
    /// let mut cache = Cache::new();
    /// println!("Max settings: {}", cache.settings().max_messages);
    /// # }
    /// ```
    pub fn settings(&self) -> SettingsRef<'_> {
        CacheRef::from_guard(self.settings.read())
    }

    /// Sets the maximum amount of messages per channel to cache.
    ///
    /// By default, no messages will be cached.
    pub fn set_max_messages(&self, max: usize) {
        self.settings.write().max_messages = max;
    }

    /// Retrieves a [`User`] from the cache's [`Self::users`] map, if it exists.
    ///
    /// The only advantage of this method is that you can pass in anything that is indirectly a
    /// [`UserId`].
    ///
    /// # Examples
    ///
    /// Retrieve a user from the cache and print their name:
    ///
    /// ```rust,no_run
    /// # use serenity::client::Context;
    /// #
    /// # async fn test(context: &Context) -> Result<(), Box<dyn std::error::Error>> {
    /// if let Some(user) = context.cache.user(7) {
    ///     println!("User with Id 7 is currently named {}", user.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn user<U: Into<UserId>>(&self, user_id: U) -> Option<UserRef<'_>> {
        self._user(user_id.into())
    }

    #[cfg(feature = "temp_cache")]
    fn _user(&self, user_id: UserId) -> Option<UserRef<'_>> {
        if let Some(user) = self.users.get(&user_id) {
            Some(CacheRef::from_ref(user))
        } else {
            self.temp_users.get(&user_id).map(CacheRef::from_arc)
        }
    }

    #[cfg(not(feature = "temp_cache"))]
    fn _user(&self, user_id: UserId) -> Option<UserRef<'_>> {
        self.users.get(&user_id).map(CacheRef::from_ref)
    }

    /// Clones all users and returns them.
    #[inline]
    pub fn users(&self) -> ReadOnlyMapRef<'_, UserId, User> {
        self.users.as_read_only()
    }

    /// Returns the amount of cached users.
    #[inline]
    pub fn user_count(&self) -> usize {
        self.users.len()
    }

    /// This method provides a reference to the user used by the bot.
    #[inline]
    pub fn current_user(&self) -> CurrentUserRef<'_> {
        CacheRef::from_guard(self.user.read())
    }

    /// Returns a channel category matching the given ID
    #[deprecated = "Use Cache::guild, Guild::channels, and GuildChannel::kind"]
    pub fn category(&self, channel_id: ChannelId) -> Option<GuildChannelRef<'_>> {
        #[allow(deprecated)]
        let channel = self.channel(channel_id)?;
        if channel.kind == ChannelType::Category {
            Some(channel)
        } else {
            None
        }
    }

    /// Returns the parent category of the given channel ID.
    #[deprecated = "Use Cache::guild, Guild::channels, and GuildChannel::parent_id"]
    pub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId> {
        #[allow(deprecated)]
        self.channel(channel_id)?.parent_id
    }

    /// Clones all channel categories in the given guild and returns them.
    pub fn guild_categories(&self, guild_id: GuildId) -> Option<HashMap<ChannelId, GuildChannel>> {
        let guild = self.guilds.get(&guild_id)?;
        Some(
            guild
                .channels
                .iter()
                .filter(|(_id, channel)| channel.kind == ChannelType::Category)
                .map(|(id, channel)| (*id, channel.clone()))
                .collect(),
        )
    }

    /// Updates the cache with the update implementation for an event or other custom update
    /// implementation.
    ///
    /// Refer to the documentation for [`CacheUpdate`] for more information.
    ///
    /// # Examples
    ///
    /// Refer to the [`CacheUpdate` examples].
    ///
    /// [`CacheUpdate` examples]: CacheUpdate#examples
    #[instrument(skip(self, e))]
    pub fn update<E: CacheUpdate>(&self, e: &mut E) -> Option<E::Output> {
        e.update(self)
    }

    pub(crate) fn update_user_entry(&self, user: &User) {
        if let Some(users) = &self.users.0 {
            match users.entry(user.id) {
                Entry::Vacant(e) => {
                    e.insert(user.clone());
                },
                Entry::Occupied(mut e) => {
                    e.get_mut().clone_from(user);
                },
            }
        }
    }
}

impl Default for Cache {
    fn default() -> Self {
        Self::new_with_settings(Settings::default())
    }
}

#[cfg(test)]
mod test {

    use crate::cache::{Cache, CacheUpdate, Settings};
    use crate::model::prelude::*;

    #[test]
    fn test_cache_messages() {
        let settings = Settings {
            max_messages: 2,
            ..Default::default()
        };
        let cache = Cache::new_with_settings(settings);

        // Test inserting one message into a channel's message cache.
        let mut event = MessageCreateEvent {
            message: Message {
                id: MessageId::new(3),
                guild_id: Some(GuildId::new(1)),
                ..Default::default()
            },
        };

        // Check that the channel cache doesn't exist.
        assert!(!cache.messages.contains_key(&event.message.channel_id));
        // Add first message, none because message ID 2 doesn't already exist.
        assert!(event.update(&cache).is_none());
        // None, it only returns the oldest message if the cache was already full.
        assert!(event.update(&cache).is_none());
        // Assert there's only 1 message in the channel's message cache.
        assert_eq!(cache.messages.get(&event.message.channel_id).unwrap().len(), 1);

        // Add a second message, assert that channel message cache length is 2.
        event.message.id = MessageId::new(4);
        assert!(event.update(&cache).is_none());
        assert_eq!(cache.messages.get(&event.message.channel_id).unwrap().len(), 2);

        // Add a third message, the first should now be removed.
        event.message.id = MessageId::new(5);
        assert!(event.update(&cache).is_some());

        {
            let channel = cache.messages.get(&event.message.channel_id).unwrap();

            assert_eq!(channel.len(), 2);
            // Check that the first message is now removed.
            assert!(!channel.contains_key(&MessageId::new(3)));
        }

        let channel = GuildChannel {
            id: event.message.channel_id,
            guild_id: event.message.guild_id.unwrap(),
            ..Default::default()
        };

        // Add a channel delete event to the cache, the cached messages for that channel should now
        // be gone.
        let mut delete = ChannelDeleteEvent {
            channel: channel.clone(),
        };
        assert!(cache.update(&mut delete).is_some());
        assert!(!cache.messages.contains_key(&delete.channel.id));

        // Test deletion of a guild channel's message cache when a GuildDeleteEvent is received.
        let mut guild_create = GuildCreateEvent {
            guild: Guild {
                id: GuildId::new(1),
                channels: HashMap::from([(ChannelId::new(2), channel)]),
                ..Default::default()
            },
        };
        assert!(cache.update(&mut guild_create).is_none());
        assert!(cache.update(&mut event).is_none());

        let mut guild_delete = GuildDeleteEvent {
            guild: UnavailableGuild {
                id: GuildId::new(1),
                unavailable: false,
            },
        };

        // The guild existed in the cache, so the cache's guild is returned by the update.
        assert!(cache.update(&mut guild_delete).is_some());

        // Assert that the channel's message cache no longer exists.
        assert!(!cache.messages.contains_key(&ChannelId::new(2)));
    }
}