Skip to main content

djs_cache/
cache.rs

1//! The cache itself.
2
3use core::{fmt, hash::Hash, time::Duration};
4use std::sync::{Arc, PoisonError, RwLock};
5
6use dashmap::DashMap;
7use djs_model::{
8    channel::Channel,
9    emoji::{Emoji, PartialEmoji},
10    gateway::{
11        DispatchEvent, Presence, Status,
12        payload::{AvailableGuild, GuildMemberUpdate, ThreadMembersUpdate},
13    },
14    guild::{Guild, Member, PartialMember, Role},
15    guild_scheduled_event::GuildScheduledEvent,
16    id::{
17        ChannelId, EmojiId, GuildId, MessageId, RoleId, ScheduledEventId, SoundboardSoundId,
18        StageInstanceId, StickerId, UserId,
19    },
20    interaction::Interaction,
21    message::{Message, Reaction},
22    soundboard::SoundboardSound,
23    stage_instance::StageInstance,
24    sticker::Sticker,
25    user::{CurrentUser, User},
26    util::Timestamp,
27    voice::VoiceState,
28};
29
30use crate::{
31    Backend, CacheConfig, CacheView, CachedGuild, CachedMember, CachedMessage, CachedPresence,
32    CachedUser, ChannelView, DashMapBackend, GuildView, Previous, Resource, Store, UpdateCache,
33    config::Scope,
34    dashmap_store::Hasher,
35    limits::{ChannelScopedOf, Global, GlobalOf, Index, Scoped, ScopedOf},
36};
37
38/// An in-memory view of Discord state, kept up to date from gateway events.
39///
40/// What it keeps is set by its [`CacheConfig`] (by default guilds, channels, roles and the
41/// current user, D-152); where it keeps it by its [`Backend`] (by default
42/// [`DashMapBackend`]). Feed it every dispatch event with [`update`](Self::update) or
43/// [`update_dispatch`](Self::update_dispatch), and read it through the per-resource views
44/// ([`guilds`](Self::guilds), [`members`](Self::members), …).
45///
46/// Reads return [`Arc`]s, which hold no lock and can be kept across `.await` (D-151). The
47/// cache is `Send + Sync`: share one between all shards, for example in an `Arc`.
48///
49/// discord.js counterpart: the `cache` collections of the client's managers
50/// (`client.guilds.cache`, `guild.members.cache`, …), filled by the client's event handlers.
51///
52/// # Examples
53///
54/// ```
55/// use djs_cache::{Cache, CacheConfig, Limit};
56/// use djs_model::{gateway::payload::GuildRoleCreate, id::GuildId};
57/// # use djs_model::guild::Role;
58/// # let role: Role = serde_json::from_str(r#"{"id":"2","name":"mods","color":0,"hoist":false,
59/// #   "position":1,"permissions":"0","managed":false,"mentionable":false,"flags":0,
60/// #   "colors":{"primary_color":0,"secondary_color":null,"tertiary_color":null}}"#).unwrap();
61/// # let event: GuildRoleCreate = serde_json::from_value(serde_json::json!({
62/// #     "guild_id": "1", "role": role })).unwrap();
63///
64/// let cache = Cache::with_config(CacheConfig::builder().members(Limit::Max(1_000)).build());
65///
66/// // `event` is a `GUILD_ROLE_CREATE` received from the gateway.
67/// let previous = cache.update(&event);
68/// assert!(previous.is_none());
69///
70/// let role = cache.roles(GuildId::new(1)).get(event.role.id).unwrap();
71/// assert_eq!(role.name, "mods");
72/// ```
73pub struct Cache<B: Backend = DashMapBackend> {
74    config: CacheConfig,
75    backend: B,
76    current_user: RwLock<Option<Arc<CurrentUser>>>,
77    unavailable_guilds: DashMap<GuildId, (), Hasher>,
78    guilds: Option<GlobalOf<GuildId, CachedGuild, B>>,
79    channels: Option<GlobalOf<ChannelId, Channel, B>>,
80    /// The channels of each guild, for listing and for dropping a deleted guild's channels.
81    guild_channels: Index<GuildId, ChannelId>,
82    roles: Option<ScopedOf<RoleId, Role, B>>,
83    emojis: Option<ScopedOf<EmojiId, Emoji, B>>,
84    stickers: Option<ScopedOf<StickerId, Sticker, B>>,
85    members: Option<ScopedOf<UserId, CachedMember, B>>,
86    users: Option<GlobalOf<UserId, CachedUser, B>>,
87    threads: Option<ScopedOf<ChannelId, Channel, B>>,
88    messages: Option<ChannelScopedOf<MessageId, CachedMessage, B>>,
89    /// The channels of each guild that have cached messages, for dropping a deleted guild's
90    /// messages even when channels are not cached.
91    message_channels: Index<GuildId, ChannelId>,
92    presences: Option<ScopedOf<UserId, CachedPresence, B>>,
93    voice_states: Option<ScopedOf<UserId, VoiceState, B>>,
94    scheduled_events: Option<ScopedOf<ScheduledEventId, GuildScheduledEvent, B>>,
95    stage_instances: Option<ScopedOf<StageInstanceId, StageInstance, B>>,
96    soundboard_sounds: Option<ScopedOf<SoundboardSoundId, SoundboardSound, B>>,
97}
98
99// The fields above match the scopes the resources declare (D-159).
100const _: () = {
101    assert!(matches!(Resource::Guild.scope(), Scope::Cache));
102    assert!(matches!(Resource::Channel.scope(), Scope::Cache));
103    assert!(matches!(Resource::User.scope(), Scope::Cache));
104    assert!(matches!(Resource::Role.scope(), Scope::Guild));
105    assert!(matches!(Resource::Emoji.scope(), Scope::Guild));
106    assert!(matches!(Resource::Sticker.scope(), Scope::Guild));
107    assert!(matches!(Resource::Member.scope(), Scope::Guild));
108    assert!(matches!(Resource::Thread.scope(), Scope::Guild));
109    assert!(matches!(Resource::Message.scope(), Scope::Channel));
110    assert!(matches!(Resource::Presence.scope(), Scope::Guild));
111    assert!(matches!(Resource::VoiceState.scope(), Scope::Guild));
112    assert!(matches!(Resource::ScheduledEvent.scope(), Scope::Guild));
113    assert!(matches!(Resource::StageInstance.scope(), Scope::Guild));
114    assert!(matches!(Resource::SoundboardSound.scope(), Scope::Guild));
115};
116
117impl Cache {
118    /// Creates a cache with the [default configuration](CacheConfig::default) and the
119    /// [`DashMapBackend`].
120    ///
121    /// discord.js counterpart: the caches `new Client()` creates (`ClientOptions#makeCache`).
122    #[must_use]
123    pub fn new() -> Self {
124        Self::with_config(CacheConfig::default())
125    }
126
127    /// Creates a cache with `config` and the [`DashMapBackend`].
128    ///
129    /// discord.js counterpart: the `makeCache` option of `ClientOptions`, with `Options.cacheWithLimits`.
130    #[must_use]
131    pub fn with_config(config: CacheConfig) -> Self {
132        Self::with_backend(config, DashMapBackend::new())
133    }
134}
135
136impl Default for Cache {
137    fn default() -> Self {
138        Self::new()
139    }
140}
141
142impl<B: Backend> Cache<B> {
143    /// Creates a cache with `config`, keeping its resources in stores created by `backend`.
144    ///
145    /// [`Backend::store`] is called once for each enabled resource.
146    ///
147    /// discord.js counterpart: the `makeCache` option of `ClientOptions`.
148    #[must_use]
149    pub fn with_backend(config: CacheConfig, backend: B) -> Self {
150        Self {
151            current_user: RwLock::new(None),
152            unavailable_guilds: DashMap::with_hasher(Hasher::default()),
153            guilds: global(&backend, &config, Resource::Guild),
154            channels: global(&backend, &config, Resource::Channel),
155            guild_channels: Index::new(),
156            roles: scoped(&backend, &config, Resource::Role),
157            emojis: scoped(&backend, &config, Resource::Emoji),
158            stickers: scoped(&backend, &config, Resource::Sticker),
159            members: scoped(&backend, &config, Resource::Member),
160            users: global(&backend, &config, Resource::User),
161            threads: scoped(&backend, &config, Resource::Thread),
162            messages: channel_scoped(&backend, &config),
163            message_channels: Index::new(),
164            presences: scoped(&backend, &config, Resource::Presence),
165            voice_states: scoped(&backend, &config, Resource::VoiceState),
166            scheduled_events: scoped(&backend, &config, Resource::ScheduledEvent),
167            stage_instances: scoped(&backend, &config, Resource::StageInstance),
168            soundboard_sounds: scoped(&backend, &config, Resource::SoundboardSound),
169            config,
170            backend,
171        }
172    }
173
174    /// Returns the configuration.
175    ///
176    /// discord.js counterpart: the `makeCache` option of `ClientOptions`.
177    #[must_use]
178    pub const fn config(&self) -> &CacheConfig {
179        &self.config
180    }
181
182    /// Returns the backend.
183    ///
184    /// discord.js counterpart: none (discord.js caches in `Collection`s).
185    #[must_use]
186    pub const fn backend(&self) -> &B {
187        &self.backend
188    }
189
190    /// Applies a dispatch event's payload to the cache, returning the previous state of what
191    /// it changed (D-153, D-163). See [`UpdateCache`] for the events and what each returns.
192    ///
193    /// discord.js counterpart: the client's internal event handlers (`client.actions`).
194    pub fn update<E: UpdateCache>(&self, event: &E) -> E::Previous {
195        event.update_cache(self)
196    }
197
198    /// Applies any dispatch event to the cache, returning the previous state as a
199    /// [`Previous`]. Events the cache does not use return [`Previous::None`].
200    ///
201    /// discord.js counterpart: none (discord.js' managers update their caches inside the client).
202    pub fn update_dispatch(&self, event: &DispatchEvent) -> Previous {
203        crate::update::dispatch(self, event)
204    }
205
206    /// Returns the bot's own user, from `READY` and `USER_UPDATE`. Always kept.
207    ///
208    /// discord.js counterpart: `client.user`.
209    #[must_use]
210    pub fn current_user(&self) -> Option<Arc<CurrentUser>> {
211        self.current_user
212            .read()
213            .unwrap_or_else(PoisonError::into_inner)
214            .clone()
215    }
216
217    /// Returns the guilds that are unavailable: listed in `READY` but not loaded yet, or
218    /// unreachable because of a Discord outage. Their cached data, if any, is kept.
219    ///
220    /// discord.js counterpart: guilds with `Guild#available === false`.
221    #[must_use]
222    pub fn unavailable_guilds(&self) -> Vec<GuildId> {
223        self.unavailable_guilds
224            .iter()
225            .map(|entry| *entry.key())
226            .collect()
227    }
228
229    /// Returns the guilds ([`Resource::Guild`]).
230    ///
231    /// discord.js counterpart: `client.guilds.cache`.
232    #[must_use]
233    pub fn guilds(&self) -> CacheView<'_, GuildId, CachedGuild, B> {
234        CacheView::new(self.guilds.as_ref(), None)
235    }
236
237    /// Returns the channels ([`Resource::Channel`]); [`CacheView::in_guild`] lists a guild's.
238    ///
239    /// discord.js counterpart: `client.channels.cache`.
240    #[must_use]
241    pub fn channels(&self) -> CacheView<'_, ChannelId, Channel, B> {
242        CacheView::new(self.channels.as_ref(), Some(&self.guild_channels))
243    }
244
245    /// Returns the users ([`Resource::User`]).
246    ///
247    /// discord.js counterpart: `client.users.cache`.
248    #[must_use]
249    pub fn users(&self) -> CacheView<'_, UserId, CachedUser, B> {
250        CacheView::new(self.users.as_ref(), None)
251    }
252
253    /// Returns a guild's roles ([`Resource::Role`]).
254    ///
255    /// discord.js counterpart: `guild.roles.cache`.
256    #[must_use]
257    pub fn roles(&self, guild_id: GuildId) -> GuildView<'_, RoleId, Role, B> {
258        GuildView::new(self.roles.as_ref(), guild_id)
259    }
260
261    /// Returns a guild's custom emojis ([`Resource::Emoji`]).
262    ///
263    /// discord.js counterpart: `guild.emojis.cache`.
264    #[must_use]
265    pub fn emojis(&self, guild_id: GuildId) -> GuildView<'_, EmojiId, Emoji, B> {
266        GuildView::new(self.emojis.as_ref(), guild_id)
267    }
268
269    /// Returns a guild's stickers ([`Resource::Sticker`]).
270    ///
271    /// discord.js counterpart: `guild.stickers.cache`.
272    #[must_use]
273    pub fn stickers(&self, guild_id: GuildId) -> GuildView<'_, StickerId, Sticker, B> {
274        GuildView::new(self.stickers.as_ref(), guild_id)
275    }
276
277    /// Returns a guild's members ([`Resource::Member`]), by user ID.
278    ///
279    /// discord.js counterpart: `guild.members.cache`.
280    #[must_use]
281    pub fn members(&self, guild_id: GuildId) -> GuildView<'_, UserId, CachedMember, B> {
282        GuildView::new(self.members.as_ref(), guild_id)
283    }
284
285    /// Returns a guild's threads ([`Resource::Thread`]).
286    ///
287    /// discord.js counterpart: `guild.channels.cache` (threads are channels there).
288    #[must_use]
289    pub fn threads(&self, guild_id: GuildId) -> GuildView<'_, ChannelId, Channel, B> {
290        GuildView::new(self.threads.as_ref(), guild_id)
291    }
292
293    /// Returns a channel's (or thread's) messages ([`Resource::Message`]).
294    ///
295    /// discord.js counterpart: `channel.messages.cache`.
296    #[must_use]
297    pub fn messages(&self, channel_id: ChannelId) -> ChannelView<'_, MessageId, CachedMessage, B> {
298        ChannelView::new(self.messages.as_ref(), channel_id)
299    }
300
301    /// Returns a guild's presences ([`Resource::Presence`]), by user ID.
302    ///
303    /// discord.js counterpart: `guild.presences.cache`.
304    #[must_use]
305    pub fn presences(&self, guild_id: GuildId) -> GuildView<'_, UserId, CachedPresence, B> {
306        GuildView::new(self.presences.as_ref(), guild_id)
307    }
308
309    /// Returns a guild's voice states ([`Resource::VoiceState`]), by user ID. Their `member`
310    /// is always `None`: members are a resource of their own.
311    ///
312    /// discord.js counterpart: `guild.voiceStates.cache`.
313    #[must_use]
314    pub fn voice_states(&self, guild_id: GuildId) -> GuildView<'_, UserId, VoiceState, B> {
315        GuildView::new(self.voice_states.as_ref(), guild_id)
316    }
317
318    /// Returns a guild's scheduled events ([`Resource::ScheduledEvent`]).
319    ///
320    /// discord.js counterpart: `guild.scheduledEvents.cache`.
321    #[must_use]
322    pub fn scheduled_events(
323        &self,
324        guild_id: GuildId,
325    ) -> GuildView<'_, ScheduledEventId, GuildScheduledEvent, B> {
326        GuildView::new(self.scheduled_events.as_ref(), guild_id)
327    }
328
329    /// Returns a guild's stage instances ([`Resource::StageInstance`]).
330    ///
331    /// discord.js counterpart: `guild.stageInstances.cache`.
332    #[must_use]
333    pub fn stage_instances(
334        &self,
335        guild_id: GuildId,
336    ) -> GuildView<'_, StageInstanceId, StageInstance, B> {
337        GuildView::new(self.stage_instances.as_ref(), guild_id)
338    }
339
340    /// Returns a guild's soundboard sounds ([`Resource::SoundboardSound`]).
341    ///
342    /// discord.js counterpart: `guild.soundboardSounds.cache`.
343    #[must_use]
344    pub fn soundboard_sounds(
345        &self,
346        guild_id: GuildId,
347    ) -> GuildView<'_, SoundboardSoundId, SoundboardSound, B> {
348        GuildView::new(self.soundboard_sounds.as_ref(), guild_id)
349    }
350}
351
352/// Sweeping (D-167, D-168): each method removes the entries its filter returns `true` for and
353/// returns how many it removed. Resources kept per guild or channel pass the guild or channel
354/// to the filter. Removing a guild, channel or thread this way also drops what belongs to it,
355/// as deleting it does.
356///
357/// discord.js counterpart: `client.sweepers.sweepGuilds(filter)`, `sweepUsers(filter)`, ….
358///
359/// # Examples
360///
361/// ```
362/// use djs_cache::{Cache, CacheConfig, Limit};
363///
364/// let cache = Cache::with_config(CacheConfig::builder().users(Limit::Unlimited).build());
365/// // Forget every bot user.
366/// let swept = cache.sweep_users(|user| user.bot);
367/// assert_eq!(swept, 0);
368/// ```
369impl<B: Backend> Cache<B> {
370    /// Sweeps guilds, with everything in them.
371    ///
372    /// discord.js counterpart: none (discord.js does not sweep guilds).
373    pub fn sweep_guilds(&self, mut filter: impl FnMut(&CachedGuild) -> bool) -> usize {
374        let Some(guilds) = &self.guilds else { return 0 };
375        let mut swept = Vec::new();
376        let count = guilds.sweep(&mut |id, guild| {
377            let sweep = filter(guild);
378            if sweep {
379                swept.push(*id);
380            }
381            sweep
382        });
383        for id in swept {
384            self.unavailable_guilds.remove(&id);
385            self.remove_guild_children(id);
386        }
387        count
388    }
389
390    /// Sweeps channels, with their messages.
391    ///
392    /// discord.js counterpart: none (discord.js does not sweep channels).
393    pub fn sweep_channels(&self, mut filter: impl FnMut(&Channel) -> bool) -> usize {
394        let Some(channels) = &self.channels else {
395            return 0;
396        };
397        let mut swept = Vec::new();
398        let count = channels.sweep(&mut |id, channel| {
399            let sweep = filter(channel);
400            if sweep {
401                swept.push((*id, channel.guild_id()));
402            }
403            sweep
404        });
405        for (id, guild_id) in swept {
406            if let Some(guild_id) = guild_id {
407                self.guild_channels.remove(guild_id, id);
408            }
409            self.remove_messages_of(guild_id, id);
410        }
411        count
412    }
413
414    /// Sweeps users. Members keep their own reference to their user.
415    ///
416    /// discord.js counterpart: `Sweepers#sweepUsers`.
417    pub fn sweep_users(&self, mut filter: impl FnMut(&CachedUser) -> bool) -> usize {
418        self.users
419            .as_ref()
420            .map_or(0, |users| users.sweep(&mut |_, user| filter(user)))
421    }
422
423    /// Sweeps threads, with their messages.
424    ///
425    /// discord.js counterpart: `Sweepers#sweepThreads`.
426    pub fn sweep_threads(&self, mut filter: impl FnMut(GuildId, &Channel) -> bool) -> usize {
427        let Some(threads) = &self.threads else {
428            return 0;
429        };
430        let mut swept = Vec::new();
431        let count = threads.sweep(&mut |guild_id, thread| {
432            let sweep = filter(guild_id, thread);
433            if sweep {
434                swept.push((guild_id, thread.id()));
435            }
436            sweep
437        });
438        for (guild_id, id) in swept {
439            self.remove_messages_of(Some(guild_id), id);
440        }
441        count
442    }
443
444    /// Sweeps threads archived more than `lifetime` ago.
445    ///
446    /// discord.js counterpart: the default `threads` sweeper
447    /// (`Sweepers.archivedThreadSweepFilter(lifetime)`).
448    pub fn sweep_archived_threads(&self, lifetime: Duration) -> usize {
449        let cutoff = cutoff(lifetime);
450        self.sweep_threads(|_, thread| {
451            thread.as_thread().is_some_and(|thread| {
452                thread.thread_metadata.archived
453                    && thread.thread_metadata.archive_timestamp.as_unix_micros() < cutoff
454            })
455        })
456    }
457
458    /// Sweeps messages.
459    ///
460    /// discord.js counterpart: `Sweepers#sweepMessages`.
461    pub fn sweep_messages(
462        &self,
463        mut filter: impl FnMut(ChannelId, &CachedMessage) -> bool,
464    ) -> usize {
465        self.messages.as_ref().map_or(0, |messages| {
466            messages.sweep(&mut |channel_id, message| filter(channel_id, message))
467        })
468    }
469
470    /// Sweeps messages last edited (or, if never edited, sent) more than `lifetime` ago.
471    ///
472    /// discord.js counterpart: `Sweepers.filterByLifetime` for messages, which also compares
473    /// the edit time first.
474    pub fn sweep_messages_older_than(&self, lifetime: Duration) -> usize {
475        let cutoff = cutoff(lifetime);
476        self.sweep_messages(|_, message| {
477            message
478                .edited_timestamp
479                .unwrap_or(message.timestamp)
480                .as_unix_micros()
481                < cutoff
482        })
483    }
484}
485
486/// Sweeps of the resources kept per guild.
487macro_rules! sweep_per_guild {
488    ($($(#[$doc:meta])* $method:ident: $field:ident => $value:ty;)*) => {
489        impl<B: Backend> Cache<B> {$(
490            $(#[$doc])*
491            pub fn $method(&self, mut filter: impl FnMut(GuildId, &$value) -> bool) -> usize {
492                self.$field.as_ref().map_or(0, |entries| {
493                    entries.sweep(&mut |guild_id, value| filter(guild_id, value))
494                })
495            }
496        )*}
497    };
498}
499
500sweep_per_guild! {
501    /// Sweeps roles.
502    sweep_roles: roles => Role;
503    /// Sweeps custom emojis.
504    sweep_emojis: emojis => Emoji;
505    /// Sweeps stickers.
506    sweep_stickers: stickers => Sticker;
507    /// Sweeps members.
508    sweep_members: members => CachedMember;
509    /// Sweeps presences.
510    sweep_presences: presences => CachedPresence;
511    /// Sweeps voice states.
512    sweep_voice_states: voice_states => VoiceState;
513    /// Sweeps scheduled events.
514    sweep_scheduled_events: scheduled_events => GuildScheduledEvent;
515    /// Sweeps stage instances.
516    sweep_stage_instances: stage_instances => StageInstance;
517    /// Sweeps soundboard sounds.
518    sweep_soundboard_sounds: soundboard_sounds => SoundboardSound;
519}
520
521/// The Unix time, in microseconds, `lifetime` before now.
522fn cutoff(lifetime: Duration) -> i64 {
523    let lifetime = i64::try_from(lifetime.as_micros()).unwrap_or(i64::MAX);
524    Timestamp::now().as_unix_micros().saturating_sub(lifetime)
525}
526
527/// The changes the event handlers in `update.rs` make.
528impl<B: Backend> Cache<B> {
529    pub(crate) fn set_current_user(&self, user: &CurrentUser) -> Option<Arc<CurrentUser>> {
530        self.current_user
531            .write()
532            .unwrap_or_else(PoisonError::into_inner)
533            .replace(Arc::new(user.clone()))
534    }
535
536    pub(crate) fn mark_unavailable(&self, guild_id: GuildId) {
537        self.unavailable_guilds.insert(guild_id, ());
538    }
539
540    /// `GUILD_CREATE` of an available guild.
541    pub(crate) fn insert_guild(&self, guild: &AvailableGuild) -> Option<Arc<CachedGuild>> {
542        let id = guild.guild.id;
543        self.unavailable_guilds.remove(&id);
544        for channel in &guild.channels {
545            self.insert_channel(channel, Some(id));
546        }
547        replace(self.roles.as_ref(), id, &guild.guild.roles, |role| role.id);
548        replace(self.emojis.as_ref(), id, &guild.guild.emojis, |emoji| {
549            emoji.id
550        });
551        replace(
552            self.stickers.as_ref(),
553            id,
554            &guild.guild.stickers,
555            |sticker| sticker.id,
556        );
557        for member in &guild.members {
558            self.upsert_member(id, member);
559        }
560        if let Some(threads) = &self.threads {
561            for thread in &guild.threads {
562                let mut thread = thread.clone();
563                set_guild_id(&mut thread, id);
564                threads.insert(id, thread.id(), Arc::new(thread));
565            }
566        }
567        for presence in &guild.presences {
568            self.update_presence(id, presence);
569        }
570        if let Some(voice_states) = &self.voice_states {
571            for state in guild
572                .voice_states
573                .iter()
574                .filter(|state| state.channel_id.is_some())
575            {
576                voice_states.insert(id, state.user_id, Arc::new(stripped_voice_state(state, id)));
577            }
578        }
579        replace(
580            self.stage_instances.as_ref(),
581            id,
582            &guild.stage_instances,
583            |stage| stage.id,
584        );
585        replace(
586            self.scheduled_events.as_ref(),
587            id,
588            &guild.guild_scheduled_events,
589            |event| event.id,
590        );
591        replace(
592            self.soundboard_sounds.as_ref(),
593            id,
594            &guild.soundboard_sounds,
595            |sound| sound.sound_id,
596        );
597        self.put_guild(Arc::new(CachedGuild::from_available(guild)))
598    }
599
600    /// `GUILD_UPDATE`. The guild's roles, emojis and stickers are replaced by the update's,
601    /// unless a list is empty (Discord may omit them; their own events cover removals).
602    pub(crate) fn update_guild(&self, guild: &Guild) -> Option<Arc<CachedGuild>> {
603        if !guild.roles.is_empty() {
604            replace(self.roles.as_ref(), guild.id, &guild.roles, |role| role.id);
605        }
606        if !guild.emojis.is_empty() {
607            replace(self.emojis.as_ref(), guild.id, &guild.emojis, |emoji| {
608                emoji.id
609            });
610        }
611        if !guild.stickers.is_empty() {
612            replace(
613                self.stickers.as_ref(),
614                guild.id,
615                &guild.stickers,
616                |sticker| sticker.id,
617            );
618        }
619        let guilds = self.guilds.as_ref()?;
620        let previous = guilds.get(&guild.id)?;
621        let updated = CachedGuild::updated(guild, &previous);
622        guilds.insert(guild.id, Arc::new(updated)).previous
623    }
624
625    /// `GUILD_DELETE`: the bot left the guild (`unavailable == false`), or the guild is in an
626    /// outage, in which case its data stays.
627    pub(crate) fn remove_guild(&self, id: GuildId, unavailable: bool) -> Option<Arc<CachedGuild>> {
628        if unavailable {
629            self.mark_unavailable(id);
630            return None;
631        }
632        self.unavailable_guilds.remove(&id);
633        self.remove_guild_children(id);
634        self.guilds.as_ref()?.remove(&id)
635    }
636
637    fn put_guild(&self, guild: Arc<CachedGuild>) -> Option<Arc<CachedGuild>> {
638        let guilds = self.guilds.as_ref()?;
639        let inserted = guilds.insert(guild.id, guild);
640        if let Some((evicted, _)) = inserted.evicted {
641            self.remove_guild_children(evicted);
642        }
643        inserted.previous
644    }
645
646    /// Drops everything cached for a guild (it was deleted, or evicted by the guild limit).
647    fn remove_guild_children(&self, id: GuildId) {
648        if let Some(channels) = &self.channels {
649            for channel in self.guild_channels.remove_parent(id) {
650                channels.remove(&channel);
651            }
652        }
653        remove_all(self.roles.as_ref(), id);
654        remove_all(self.emojis.as_ref(), id);
655        remove_all(self.stickers.as_ref(), id);
656        remove_all(self.members.as_ref(), id);
657        remove_all(self.threads.as_ref(), id);
658        remove_all(self.presences.as_ref(), id);
659        remove_all(self.voice_states.as_ref(), id);
660        remove_all(self.scheduled_events.as_ref(), id);
661        remove_all(self.stage_instances.as_ref(), id);
662        remove_all(self.soundboard_sounds.as_ref(), id);
663        if let Some(messages) = &self.messages {
664            for channel in self.message_channels.remove_parent(id) {
665                messages.remove_parent(channel);
666            }
667        }
668    }
669
670    /// Adds a guild member to the guild's member count.
671    pub(crate) fn count_member(&self, guild_id: GuildId, joined: bool) {
672        let Some(guilds) = &self.guilds else { return };
673        let Some(guild) = guilds.get(&guild_id) else {
674            return;
675        };
676        let mut updated = CachedGuild::clone(&guild);
677        updated.member_count = if joined {
678            updated.member_count.saturating_add(1)
679        } else {
680            updated.member_count.saturating_sub(1)
681        };
682        guilds.insert(guild_id, Arc::new(updated));
683    }
684
685    /// `CHANNEL_CREATE` / `CHANNEL_UPDATE`, and the channels of a `GUILD_CREATE` (which lack
686    /// their `guild_id`; the cached copy gets it). Threads are a resource of their own and are
687    /// skipped here.
688    pub(crate) fn insert_channel(
689        &self,
690        channel: &Channel,
691        guild_id: Option<GuildId>,
692    ) -> Option<Arc<Channel>> {
693        if channel.as_thread().is_some() || self.channels.is_none() {
694            return None;
695        }
696        let mut channel = channel.clone();
697        if let Some(guild_id) = guild_id {
698            set_guild_id(&mut channel, guild_id);
699        }
700        self.put_channel(Arc::new(channel))
701    }
702
703    /// Stores a guild or DM channel (not a thread), indexing it under its guild.
704    fn put_channel(&self, channel: Arc<Channel>) -> Option<Arc<Channel>> {
705        let channels = self.channels.as_ref()?;
706        if let Some(guild_id) = channel.guild_id() {
707            self.guild_channels.insert(guild_id, channel.id());
708        }
709        let inserted = channels.insert(channel.id(), channel);
710        if let Some((id, evicted)) = &inserted.evicted
711            && let Some(guild_id) = evicted.guild_id()
712        {
713            self.guild_channels.remove(guild_id, *id);
714        }
715        inserted.previous
716    }
717
718    /// `CHANNEL_DELETE`. The channel's messages go too.
719    pub(crate) fn remove_channel(&self, channel: &Channel) -> Option<Arc<Channel>> {
720        self.remove_messages_of(channel.guild_id(), channel.id());
721        let removed = self.channels.as_ref()?.remove(&channel.id());
722        let guild_id = channel
723            .guild_id()
724            .or_else(|| removed.as_ref().and_then(|removed| removed.guild_id()));
725        if let Some(guild_id) = guild_id {
726            self.guild_channels.remove(guild_id, channel.id());
727        }
728        removed
729    }
730
731    /// `CHANNEL_PINS_UPDATE`.
732    pub(crate) fn update_pins(
733        &self,
734        channel_id: ChannelId,
735        last_pin_timestamp: Option<Timestamp>,
736    ) -> Option<Arc<Channel>> {
737        let channels = self.channels.as_ref()?;
738        let mut channel = Channel::clone(&*channels.get(&channel_id)?);
739        if !set_last_pin_timestamp(&mut channel, last_pin_timestamp) {
740            return None;
741        }
742        channels.insert(channel_id, Arc::new(channel)).previous
743    }
744
745    pub(crate) fn insert_role(&self, guild_id: GuildId, role: &Role) -> Option<Arc<Role>> {
746        self.roles
747            .as_ref()?
748            .insert(guild_id, role.id, Arc::new(role.clone()))
749            .previous
750    }
751
752    pub(crate) fn remove_role(&self, guild_id: GuildId, role_id: RoleId) -> Option<Arc<Role>> {
753        self.roles.as_ref()?.remove(guild_id, role_id)
754    }
755
756    pub(crate) fn replace_emojis(&self, guild_id: GuildId, emojis: &[Emoji]) -> Vec<Arc<Emoji>> {
757        replace(self.emojis.as_ref(), guild_id, emojis, |emoji| emoji.id)
758    }
759
760    pub(crate) fn replace_stickers(
761        &self,
762        guild_id: GuildId,
763        stickers: &[Sticker],
764    ) -> Vec<Arc<Sticker>> {
765        replace(self.stickers.as_ref(), guild_id, stickers, |sticker| {
766            sticker.id
767        })
768    }
769
770    /// `GUILD_MEMBER_ADD`, the members of `GUILD_CREATE` and `GUILD_MEMBERS_CHUNK`.
771    pub(crate) fn upsert_member(
772        &self,
773        guild_id: GuildId,
774        member: &Member,
775    ) -> Option<Arc<CachedMember>> {
776        let Some(members) = &self.members else {
777            self.cache_user(&member.user);
778            return None;
779        };
780        let user = self.share_user(&member.user);
781        let id = user.id;
782        members
783            .insert(
784                guild_id,
785                id,
786                Arc::new(CachedMember::new(guild_id, member, user)),
787            )
788            .previous
789    }
790
791    /// `GUILD_MEMBER_UPDATE`. A member that was not cached is added, like discord.js does.
792    pub(crate) fn update_member(&self, update: &GuildMemberUpdate) -> Option<Arc<CachedMember>> {
793        let Some(members) = &self.members else {
794            self.cache_user(&update.user);
795            return None;
796        };
797        let user = self.share_user(&update.user);
798        let id = user.id;
799        let previous = members.get(update.guild_id, id);
800        let updated = CachedMember::updated(update, user, previous.as_deref());
801        members
802            .insert(update.guild_id, id, Arc::new(updated))
803            .previous
804    }
805
806    /// `GUILD_MEMBER_REMOVE`. The user stays cached, like in discord.js.
807    pub(crate) fn remove_member(
808        &self,
809        guild_id: GuildId,
810        user: &User,
811    ) -> Option<Arc<CachedMember>> {
812        self.cache_user(user);
813        self.members.as_ref()?.remove(guild_id, user.id)
814    }
815
816    /// `THREAD_CREATE` / `THREAD_UPDATE`.
817    pub(crate) fn insert_thread(&self, thread: &Channel) -> Option<Arc<Channel>> {
818        let threads = self.threads.as_ref()?;
819        let guild_id = thread.guild_id()?;
820        threads
821            .insert(guild_id, thread.id(), Arc::new(thread.clone()))
822            .previous
823    }
824
825    /// `THREAD_MEMBERS_UPDATE` (D-173): the added members are cached as guild members, and a
826    /// cached thread gets the new member count.
827    pub(crate) fn update_thread_members(
828        &self,
829        update: &ThreadMembersUpdate,
830    ) -> Option<Arc<Channel>> {
831        for added in &update.added_members {
832            if let Some(member) = &added.member.member {
833                self.upsert_member(update.guild_id, member);
834            }
835        }
836        let threads = self.threads.as_ref()?;
837        let mut thread = Channel::clone(&*threads.get(update.guild_id, update.id)?);
838        if !set_member_count(&mut thread, update.member_count) {
839            return None;
840        }
841        threads
842            .insert(update.guild_id, update.id, Arc::new(thread))
843            .previous
844    }
845
846    /// `THREAD_DELETE`. The thread's messages go too.
847    pub(crate) fn remove_thread(&self, guild_id: GuildId, id: ChannelId) -> Option<Arc<Channel>> {
848        self.remove_messages_of(Some(guild_id), id);
849        self.threads.as_ref()?.remove(guild_id, id)
850    }
851
852    /// `THREAD_LIST_SYNC`: the active threads of the synced parent channels (all of the
853    /// guild's when `parents` is `None`) are replaced. Returns the threads it replaced.
854    pub(crate) fn sync_threads(
855        &self,
856        guild_id: GuildId,
857        parents: Option<&[ChannelId]>,
858        synced: &[Channel],
859    ) -> Vec<Arc<Channel>> {
860        let Some(threads) = &self.threads else {
861            return Vec::new();
862        };
863        let mut previous = Vec::new();
864        for thread in threads.values_of(guild_id) {
865            let in_sync = parents.is_none_or(|parents| {
866                thread
867                    .parent_id()
868                    .is_some_and(|parent| parents.contains(&parent))
869            });
870            let active = thread
871                .as_thread()
872                .is_some_and(|thread| !thread.thread_metadata.archived);
873            if in_sync && active {
874                previous.extend(threads.remove(guild_id, thread.id()));
875            }
876        }
877        for thread in synced {
878            threads.insert(guild_id, thread.id(), Arc::new(thread.clone()));
879        }
880        previous
881    }
882
883    /// `MESSAGE_CREATE`. The author is cached as a user (unless it is a webhook) and, with
884    /// the message's member data, as a member.
885    pub(crate) fn insert_message(&self, message: &Message) -> Option<Arc<CachedMessage>> {
886        let author = if message.webhook_id.is_some() {
887            Arc::new(CachedUser::new(&message.author))
888        } else if self.messages.is_some() || self.members.is_some() {
889            self.share_user(&message.author)
890        } else {
891            self.cache_user(&message.author);
892            return None;
893        };
894        if let (Some(guild_id), Some(member), Some(members)) =
895            (message.guild_id, &message.member, &self.members)
896        {
897            put_partial_member(members, guild_id, member, Arc::clone(&author));
898        }
899        let messages = self.messages.as_ref()?;
900        if let Some(guild_id) = message.guild_id {
901            self.message_channels.insert(guild_id, message.channel_id);
902        }
903        let cached = CachedMessage::new(message, author);
904        messages
905            .insert(message.channel_id, message.id, Arc::new(cached))
906            .previous
907    }
908
909    /// `MESSAGE_UPDATE` (the full new message). Only a cached message is updated, like in
910    /// discord.js; the author and member are cached either way.
911    pub(crate) fn update_message(&self, message: &Message) -> Option<Arc<CachedMessage>> {
912        let cached = self
913            .messages
914            .as_ref()
915            .is_some_and(|messages| messages.get(message.channel_id, message.id).is_some());
916        if cached {
917            self.insert_message(message)
918        } else {
919            if message.webhook_id.is_none() {
920                self.cache_user(&message.author);
921            }
922            None
923        }
924    }
925
926    /// `MESSAGE_DELETE`.
927    pub(crate) fn remove_message(
928        &self,
929        channel_id: ChannelId,
930        id: MessageId,
931    ) -> Option<Arc<CachedMessage>> {
932        self.messages.as_ref()?.remove(channel_id, id)
933    }
934
935    fn remove_messages_of(&self, guild_id: Option<GuildId>, channel_id: ChannelId) {
936        if let Some(messages) = &self.messages {
937            messages.remove_parent(channel_id);
938            if let Some(guild_id) = guild_id {
939                self.message_channels.remove(guild_id, channel_id);
940            }
941        }
942    }
943
944    /// The reaction events (D-166): changes a cached message's reactions, returning the
945    /// message before.
946    pub(crate) fn react(
947        &self,
948        channel_id: ChannelId,
949        message_id: MessageId,
950        change: ReactionChange<'_>,
951    ) -> Option<Arc<CachedMessage>> {
952        let messages = self.messages.as_ref()?;
953        let mut message = CachedMessage::clone(&*messages.get(channel_id, message_id)?);
954        let me = self.current_user().map(|user| user.id);
955        change.apply(&mut message.reactions, me);
956        messages
957            .insert(channel_id, message_id, Arc::new(message))
958            .previous
959    }
960
961    /// `INTERACTION_CREATE` (D-173): the interaction's user and member, and the resolved users
962    /// and members, like discord.js. Resolved channels are partial and not cached.
963    pub(crate) fn apply_interaction(&self, interaction: &Interaction) -> Option<Arc<CachedMember>> {
964        if let Some(resolved) = interaction.data.resolved() {
965            for (id, user) in &resolved.users {
966                match (interaction.guild_id, resolved.members.get(id)) {
967                    (Some(guild_id), Some(member)) => {
968                        // Resolved members carry neither `deaf` nor `mute`.
969                        self.upsert_partial_member(guild_id, &member.member, user, true);
970                    }
971                    _ => self.cache_user(user),
972                }
973            }
974        }
975        if let (Some(guild_id), Some(member)) = (interaction.guild_id, &interaction.member) {
976            self.upsert_partial_member(guild_id, &member.member, member.user.as_ref()?, false)
977        } else {
978            if let Some(user) = &interaction.user {
979                self.cache_user(user);
980            }
981            None
982        }
983    }
984
985    /// Caches a partial member with its user. With `keep_voice`, a cached member keeps its
986    /// `deaf` and `mute` (absent from the partial member).
987    fn upsert_partial_member(
988        &self,
989        guild_id: GuildId,
990        member: &PartialMember,
991        user: &User,
992        keep_voice: bool,
993    ) -> Option<Arc<CachedMember>> {
994        let Some(members) = &self.members else {
995            self.cache_user(user);
996            return None;
997        };
998        let user = self.share_user(user);
999        let id = user.id;
1000        let mut cached = CachedMember::from_partial(guild_id, member, user);
1001        if keep_voice && let Some(previous) = members.get(guild_id, id) {
1002            cached.deaf = previous.deaf;
1003            cached.mute = previous.mute;
1004        }
1005        members.insert(guild_id, id, Arc::new(cached)).previous
1006    }
1007
1008    /// `PRESENCE_UPDATE` and the presences of `GUILD_CREATE` / `GUILD_MEMBERS_CHUNK`. An
1009    /// offline member's presence is removed.
1010    pub(crate) fn update_presence(
1011        &self,
1012        guild_id: GuildId,
1013        presence: &Presence,
1014    ) -> Option<Arc<CachedPresence>> {
1015        let presences = self.presences.as_ref()?;
1016        if presence.status == Status::Offline {
1017            return presences.remove(guild_id, presence.user.id);
1018        }
1019        presences
1020            .insert(
1021                guild_id,
1022                presence.user.id,
1023                Arc::new(CachedPresence::new(guild_id, presence)),
1024            )
1025            .previous
1026    }
1027
1028    /// `VOICE_STATE_UPDATE`: a state without a channel means the user left voice. The
1029    /// state's member is cached as a member.
1030    pub(crate) fn update_voice_state(&self, state: &VoiceState) -> Option<Arc<VoiceState>> {
1031        let guild_id = state.guild_id?;
1032        if let Some(member) = &state.member {
1033            self.upsert_member(guild_id, member);
1034        }
1035        let voice_states = self.voice_states.as_ref()?;
1036        if state.channel_id.is_none() {
1037            return voice_states.remove(guild_id, state.user_id);
1038        }
1039        voice_states
1040            .insert(
1041                guild_id,
1042                state.user_id,
1043                Arc::new(stripped_voice_state(state, guild_id)),
1044            )
1045            .previous
1046    }
1047
1048    pub(crate) fn put_scheduled_event(
1049        &self,
1050        event: &GuildScheduledEvent,
1051    ) -> Option<Arc<GuildScheduledEvent>> {
1052        put(
1053            self.scheduled_events.as_ref(),
1054            event.guild_id,
1055            event.id,
1056            event,
1057        )
1058    }
1059
1060    pub(crate) fn remove_scheduled_event(
1061        &self,
1062        event: &GuildScheduledEvent,
1063    ) -> Option<Arc<GuildScheduledEvent>> {
1064        self.scheduled_events
1065            .as_ref()?
1066            .remove(event.guild_id, event.id)
1067    }
1068
1069    pub(crate) fn put_stage_instance(&self, stage: &StageInstance) -> Option<Arc<StageInstance>> {
1070        put(
1071            self.stage_instances.as_ref(),
1072            stage.guild_id,
1073            stage.id,
1074            stage,
1075        )
1076    }
1077
1078    pub(crate) fn remove_stage_instance(
1079        &self,
1080        stage: &StageInstance,
1081    ) -> Option<Arc<StageInstance>> {
1082        self.stage_instances
1083            .as_ref()?
1084            .remove(stage.guild_id, stage.id)
1085    }
1086
1087    pub(crate) fn put_soundboard_sound(
1088        &self,
1089        guild_id: GuildId,
1090        sound: &SoundboardSound,
1091    ) -> Option<Arc<SoundboardSound>> {
1092        put(
1093            self.soundboard_sounds.as_ref(),
1094            guild_id,
1095            sound.sound_id,
1096            sound,
1097        )
1098    }
1099
1100    pub(crate) fn remove_soundboard_sound(
1101        &self,
1102        guild_id: GuildId,
1103        id: SoundboardSoundId,
1104    ) -> Option<Arc<SoundboardSound>> {
1105        self.soundboard_sounds.as_ref()?.remove(guild_id, id)
1106    }
1107
1108    pub(crate) fn replace_soundboard_sounds(
1109        &self,
1110        guild_id: GuildId,
1111        sounds: &[SoundboardSound],
1112    ) -> Vec<Arc<SoundboardSound>> {
1113        replace(self.soundboard_sounds.as_ref(), guild_id, sounds, |sound| {
1114            sound.sound_id
1115        })
1116    }
1117
1118    /// Caches a user seen in an event, if users are cached.
1119    fn cache_user(&self, user: &User) {
1120        if self.users.is_some() {
1121            self.share_user(user);
1122        }
1123    }
1124
1125    /// Returns an `Arc` of `user`: the user resource's own when it holds an equal user (so a
1126    /// user in many guilds is stored once), else a new one, which the user resource then
1127    /// keeps.
1128    fn share_user(&self, user: &User) -> Arc<CachedUser> {
1129        let Some(users) = &self.users else {
1130            return Arc::new(CachedUser::new(user));
1131        };
1132        if let Some(cached) = users.get(&user.id)
1133            && cached.is(user)
1134        {
1135            return cached;
1136        }
1137        let shared = Arc::new(CachedUser::new(user));
1138        users.insert(user.id, Arc::clone(&shared));
1139        shared
1140    }
1141}
1142
1143/// Storing objects received from the REST API (D-230): each method converts the object to
1144/// the form the cache keeps, stores it when its resource is enabled, and returns it — so the
1145/// djs-rs managers hand out the same type whether a value came from the cache or from Discord
1146/// (D-233).
1147impl<B: Backend> Cache<B> {
1148    /// Stores a user, for example from Get User, and returns it as cached.
1149    ///
1150    /// With [`Resource::User`] enabled, an equal cached user is reused, so a user stays stored
1151    /// once.
1152    ///
1153    /// discord.js counterpart: what `UserManager#fetch` adds to the cache.
1154    ///
1155    /// # Examples
1156    ///
1157    /// ```
1158    /// # use djs_cache::{Cache, CacheConfig, Limit};
1159    /// # let user: djs_model::user::User = serde_json::from_str(
1160    /// #     r#"{"id":"1","username":"nelly","discriminator":"0","global_name":null,"avatar":null}"#,
1161    /// # ).unwrap();
1162    /// let cache = Cache::with_config(CacheConfig::builder().users(Limit::Unlimited).build());
1163    /// let cached = cache.store_user(&user);
1164    /// assert_eq!(cached.username, "nelly");
1165    /// assert!(cache.users().get(user.id).is_some());
1166    /// ```
1167    pub fn store_user(&self, user: &User) -> Arc<CachedUser> {
1168        self.share_user(user)
1169    }
1170
1171    /// Stores a member of `guild_id`, for example from Get Guild Member, and returns it as
1172    /// cached ([`Resource::Member`]; its user is stored as by [`store_user`](Self::store_user)).
1173    ///
1174    /// Unlike `GUILD_MEMBER_ADD`, this does not count a join in the guild's member count.
1175    ///
1176    /// discord.js counterpart: what `GuildMemberManager#fetch` adds to the cache.
1177    pub fn store_member(&self, guild_id: GuildId, member: &Member) -> Arc<CachedMember> {
1178        let user = self.share_user(&member.user);
1179        let id = user.id;
1180        let cached = Arc::new(CachedMember::new(guild_id, member, user));
1181        if let Some(members) = &self.members {
1182            members.insert(guild_id, id, Arc::clone(&cached));
1183        }
1184        cached
1185    }
1186
1187    /// Stores a message, for example from Get Channel Message or Create Message, and returns
1188    /// it as cached ([`Resource::Message`]; its author and member as for `MESSAGE_CREATE`).
1189    ///
1190    /// discord.js counterpart: what `MessageManager#fetch` adds to the cache.
1191    pub fn store_message(&self, message: &Message) -> Arc<CachedMessage> {
1192        let author = if message.webhook_id.is_some() {
1193            Arc::new(CachedUser::new(&message.author))
1194        } else {
1195            self.share_user(&message.author)
1196        };
1197        if let (Some(guild_id), Some(member), Some(members)) =
1198            (message.guild_id, &message.member, &self.members)
1199        {
1200            put_partial_member(members, guild_id, member, Arc::clone(&author));
1201        }
1202        let cached = Arc::new(CachedMessage::new(message, author));
1203        if let Some(messages) = &self.messages {
1204            if let Some(guild_id) = message.guild_id {
1205                self.message_channels.insert(guild_id, message.channel_id);
1206            }
1207            messages.insert(message.channel_id, message.id, Arc::clone(&cached));
1208        }
1209        cached
1210    }
1211
1212    /// Stores a channel or thread, for example from Get Channel, and returns it as cached
1213    /// ([`Resource::Channel`], or [`Resource::Thread`] for a thread in a guild).
1214    ///
1215    /// discord.js counterpart: what `ChannelManager#fetch` adds to the cache.
1216    pub fn store_channel(&self, channel: &Channel) -> Arc<Channel> {
1217        let cached = Arc::new(channel.clone());
1218        if cached.as_thread().is_some() {
1219            if let (Some(threads), Some(guild_id)) = (&self.threads, cached.guild_id()) {
1220                threads.insert(guild_id, cached.id(), Arc::clone(&cached));
1221            }
1222        } else {
1223            self.put_channel(Arc::clone(&cached));
1224        }
1225        cached
1226    }
1227
1228    /// Stores a role of `guild_id`, for example from Get Guild Role, and returns it as cached
1229    /// ([`Resource::Role`]).
1230    ///
1231    /// discord.js counterpart: what `RoleManager#fetch` adds to the cache.
1232    pub fn store_role(&self, guild_id: GuildId, role: &Role) -> Arc<Role> {
1233        let cached = Arc::new(role.clone());
1234        if let Some(roles) = &self.roles {
1235            roles.insert(guild_id, role.id, Arc::clone(&cached));
1236        }
1237        cached
1238    }
1239
1240    /// Stores a custom emoji of `guild_id`, for example from Get Guild Emoji, and returns it
1241    /// as cached ([`Resource::Emoji`]).
1242    ///
1243    /// discord.js counterpart: what `GuildEmojiManager#fetch` adds to the cache.
1244    pub fn store_emoji(&self, guild_id: GuildId, emoji: &Emoji) -> Arc<Emoji> {
1245        let cached = Arc::new(emoji.clone());
1246        if let Some(emojis) = &self.emojis {
1247            emojis.insert(guild_id, emoji.id, Arc::clone(&cached));
1248        }
1249        cached
1250    }
1251
1252    /// Stores a sticker of `guild_id`, for example from Get Guild Sticker, and returns it as
1253    /// cached ([`Resource::Sticker`]).
1254    ///
1255    /// discord.js counterpart: what `GuildStickerManager#fetch` adds to the cache.
1256    pub fn store_sticker(&self, guild_id: GuildId, sticker: &Sticker) -> Arc<Sticker> {
1257        let cached = Arc::new(sticker.clone());
1258        if let Some(stickers) = &self.stickers {
1259            stickers.insert(guild_id, sticker.id, Arc::clone(&cached));
1260        }
1261        cached
1262    }
1263
1264    /// Stores a scheduled event of `guild_id`, for example from Get Guild Scheduled Event,
1265    /// and returns it as cached ([`Resource::ScheduledEvent`]).
1266    ///
1267    /// discord.js counterpart: what `GuildScheduledEventManager#fetch` adds to the cache.
1268    pub fn store_scheduled_event(
1269        &self,
1270        guild_id: GuildId,
1271        event: &GuildScheduledEvent,
1272    ) -> Arc<GuildScheduledEvent> {
1273        let cached = Arc::new(event.clone());
1274        if let Some(events) = &self.scheduled_events {
1275            events.insert(guild_id, event.id, Arc::clone(&cached));
1276        }
1277        cached
1278    }
1279
1280    /// Stores a stage instance of `guild_id`, for example from Get Stage Instance, and
1281    /// returns it as cached ([`Resource::StageInstance`]).
1282    ///
1283    /// discord.js counterpart: what `StageInstanceManager#fetch` adds to the cache.
1284    pub fn store_stage_instance(
1285        &self,
1286        guild_id: GuildId,
1287        stage: &StageInstance,
1288    ) -> Arc<StageInstance> {
1289        let cached = Arc::new(stage.clone());
1290        if let Some(stages) = &self.stage_instances {
1291            stages.insert(guild_id, stage.id, Arc::clone(&cached));
1292        }
1293        cached
1294    }
1295
1296    /// Stores a soundboard sound of `guild_id`, for example from Get Guild Soundboard Sound,
1297    /// and returns it as cached ([`Resource::SoundboardSound`]).
1298    ///
1299    /// discord.js counterpart: what `GuildSoundboardSoundManager#fetch` adds to the cache.
1300    pub fn store_soundboard_sound(
1301        &self,
1302        guild_id: GuildId,
1303        sound: &SoundboardSound,
1304    ) -> Arc<SoundboardSound> {
1305        let cached = Arc::new(sound.clone());
1306        if let Some(sounds) = &self.soundboard_sounds {
1307            sounds.insert(guild_id, sound.sound_id, Arc::clone(&cached));
1308        }
1309        cached
1310    }
1311
1312    /// Stores a guild, for example from Get Guild, and returns it as cached
1313    /// ([`Resource::Guild`]); its roles, emojis and stickers replace the cached ones when
1314    /// sent, as for `GUILD_UPDATE`.
1315    ///
1316    /// A guild the cache already holds keeps what only `GUILD_CREATE` sends (`joined_at`,
1317    /// `large`, `member_count`); a new one takes its member count from
1318    /// `approximate_member_count` (sent with `with_counts`), or 0.
1319    ///
1320    /// discord.js counterpart: what `GuildManager#fetch` adds to the cache.
1321    pub fn store_guild(&self, guild: &Guild) -> Arc<CachedGuild> {
1322        let previous = self
1323            .guilds
1324            .as_ref()
1325            .and_then(|guilds| guilds.get(&guild.id));
1326        let cached = match previous {
1327            Some(previous) => CachedGuild::updated(guild, &previous),
1328            None => CachedGuild::new(
1329                guild,
1330                None,
1331                false,
1332                guild.approximate_member_count.unwrap_or(0),
1333            ),
1334        };
1335        let cached = Arc::new(cached);
1336        if self.guilds.is_some() {
1337            if !guild.roles.is_empty() {
1338                replace(self.roles.as_ref(), guild.id, &guild.roles, |role| role.id);
1339            }
1340            if !guild.emojis.is_empty() {
1341                replace(self.emojis.as_ref(), guild.id, &guild.emojis, |emoji| {
1342                    emoji.id
1343                });
1344            }
1345            if !guild.stickers.is_empty() {
1346                replace(
1347                    self.stickers.as_ref(),
1348                    guild.id,
1349                    &guild.stickers,
1350                    |sticker| sticker.id,
1351                );
1352            }
1353            self.put_guild(Arc::clone(&cached));
1354        }
1355        cached
1356    }
1357}
1358
1359impl<B: Backend> fmt::Debug for Cache<B> {
1360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1361        f.debug_struct("Cache")
1362            .field("config", &self.config)
1363            .field("backend", &self.backend)
1364            .field("guilds", &self.guilds().len())
1365            .field("channels", &self.channels().len())
1366            .field("users", &self.users().len())
1367            .field("members", &self.members.as_ref().map_or(0, Scoped::len))
1368            .field("messages", &self.messages.as_ref().map_or(0, Scoped::len))
1369            .finish_non_exhaustive()
1370    }
1371}
1372
1373/// Creates the store of a resource kept over the whole cache, if it is enabled.
1374fn global<K, V, B>(
1375    backend: &B,
1376    config: &CacheConfig,
1377    resource: Resource,
1378) -> Option<GlobalOf<K, V, B>>
1379where
1380    K: Eq + Hash + Copy + Send + Sync + 'static,
1381    V: Send + Sync + 'static,
1382    B: Backend,
1383{
1384    let limit = config.limit(resource);
1385    limit
1386        .is_enabled()
1387        .then(|| Global::new(backend.store(resource, limit), limit))
1388}
1389
1390/// Creates the message store (kept per channel), if messages are enabled.
1391fn channel_scoped<B: Backend>(
1392    backend: &B,
1393    config: &CacheConfig,
1394) -> Option<ChannelScopedOf<MessageId, CachedMessage, B>> {
1395    let limit = config.limit(Resource::Message);
1396    limit
1397        .is_enabled()
1398        .then(|| Scoped::new(backend.store(Resource::Message, limit), limit))
1399}
1400
1401/// Inserts a copy of `value` into a guild resource, returning the previous one.
1402fn put<K, V, S>(
1403    entries: Option<&Scoped<GuildId, K, V, S>>,
1404    guild_id: GuildId,
1405    id: K,
1406    value: &V,
1407) -> Option<Arc<V>>
1408where
1409    K: Eq + Hash + Copy,
1410    V: Clone,
1411    S: Store<(GuildId, K), V>,
1412{
1413    entries?
1414        .insert(guild_id, id, Arc::new(value.clone()))
1415        .previous
1416}
1417
1418/// Caches the partial member attached to a message, with the message's author as its user.
1419fn put_partial_member<S>(
1420    members: &Scoped<GuildId, UserId, CachedMember, S>,
1421    guild_id: GuildId,
1422    member: &PartialMember,
1423    user: Arc<CachedUser>,
1424) where
1425    S: Store<(GuildId, UserId), CachedMember>,
1426{
1427    let id = user.id;
1428    let cached = CachedMember::from_partial(guild_id, member, user);
1429    members.insert(guild_id, id, Arc::new(cached));
1430}
1431
1432/// A voice state as cached: with its guild, without its member (members are a resource of
1433/// their own).
1434fn stripped_voice_state(state: &VoiceState, guild_id: GuildId) -> VoiceState {
1435    let mut state = state.clone();
1436    state.guild_id = Some(guild_id);
1437    state.member = None;
1438    state
1439}
1440
1441/// A change to a message's reactions (D-166).
1442pub(crate) enum ReactionChange<'a> {
1443    /// `MESSAGE_REACTION_ADD`.
1444    Add {
1445        emoji: &'a PartialEmoji,
1446        user_id: UserId,
1447        burst: bool,
1448        burst_colors: &'a [compact_str::CompactString],
1449    },
1450    /// `MESSAGE_REACTION_REMOVE`.
1451    Remove {
1452        emoji: &'a PartialEmoji,
1453        user_id: UserId,
1454        burst: bool,
1455    },
1456    /// `MESSAGE_REACTION_REMOVE_ALL`.
1457    RemoveAll,
1458    /// `MESSAGE_REACTION_REMOVE_EMOJI`.
1459    RemoveEmoji(&'a PartialEmoji),
1460}
1461
1462impl ReactionChange<'_> {
1463    fn apply(self, reactions: &mut Vec<Reaction>, me: Option<UserId>) {
1464        match self {
1465            Self::Add {
1466                emoji,
1467                user_id,
1468                burst,
1469                burst_colors,
1470            } => {
1471                let index = if let Some(index) = reactions
1472                    .iter()
1473                    .position(|reaction| same_emoji(&reaction.emoji, emoji))
1474                {
1475                    index
1476                } else {
1477                    reactions.push(Reaction::new(emoji.clone()));
1478                    reactions.len() - 1
1479                };
1480                let reaction = &mut reactions[index];
1481                let mine = me == Some(user_id);
1482                reaction.count += 1;
1483                if burst {
1484                    reaction.count_details.burst += 1;
1485                    reaction.me_burst |= mine;
1486                    if reaction.burst_colors.is_empty() {
1487                        reaction.burst_colors = burst_colors.to_vec();
1488                    }
1489                } else {
1490                    reaction.count_details.normal += 1;
1491                    reaction.me |= mine;
1492                }
1493            }
1494            Self::Remove {
1495                emoji,
1496                user_id,
1497                burst,
1498            } => {
1499                let Some(index) = reactions
1500                    .iter()
1501                    .position(|reaction| same_emoji(&reaction.emoji, emoji))
1502                else {
1503                    return;
1504                };
1505                let reaction = &mut reactions[index];
1506                let mine = me == Some(user_id);
1507                reaction.count = reaction.count.saturating_sub(1);
1508                if burst {
1509                    reaction.count_details.burst = reaction.count_details.burst.saturating_sub(1);
1510                    reaction.me_burst &= !mine;
1511                } else {
1512                    reaction.count_details.normal = reaction.count_details.normal.saturating_sub(1);
1513                    reaction.me &= !mine;
1514                }
1515                if reaction.count == 0 {
1516                    reactions.remove(index);
1517                }
1518            }
1519            Self::RemoveAll => reactions.clear(),
1520            Self::RemoveEmoji(emoji) => {
1521                reactions.retain(|reaction| !same_emoji(&reaction.emoji, emoji));
1522            }
1523        }
1524    }
1525}
1526
1527/// Whether two reaction emojis are the same: custom emojis by ID (their names may be missing),
1528/// Unicode emojis by the emoji itself.
1529fn same_emoji(a: &PartialEmoji, b: &PartialEmoji) -> bool {
1530    match (a.id(), b.id()) {
1531        (Some(a), Some(b)) => a == b,
1532        (None, None) => a == b,
1533        _ => false,
1534    }
1535}
1536
1537/// Creates the store of a resource kept per guild, if it is enabled.
1538fn scoped<K, V, B>(
1539    backend: &B,
1540    config: &CacheConfig,
1541    resource: Resource,
1542) -> Option<ScopedOf<K, V, B>>
1543where
1544    K: Eq + Hash + Copy + Send + Sync + 'static,
1545    V: Send + Sync + 'static,
1546    B: Backend,
1547{
1548    let limit = config.limit(resource);
1549    limit
1550        .is_enabled()
1551        .then(|| Scoped::new(backend.store(resource, limit), limit))
1552}
1553
1554/// Replaces a guild's entries of a resource (the roles of a `GUILD_CREATE`, the emojis of a
1555/// `GUILD_EMOJIS_UPDATE`, …), returning the previous ones.
1556fn replace<K, V, S>(
1557    entries: Option<&Scoped<GuildId, K, V, S>>,
1558    guild_id: GuildId,
1559    items: &[V],
1560    id: impl Fn(&V) -> K,
1561) -> Vec<Arc<V>>
1562where
1563    K: Eq + Hash + Copy,
1564    V: Clone,
1565    S: Store<(GuildId, K), V>,
1566{
1567    let Some(entries) = entries else {
1568        return Vec::new();
1569    };
1570    let previous = entries.remove_parent(guild_id);
1571    for item in items {
1572        entries.insert(guild_id, id(item), Arc::new(item.clone()));
1573    }
1574    previous
1575}
1576
1577fn remove_all<K, V, S>(entries: Option<&Scoped<GuildId, K, V, S>>, guild_id: GuildId)
1578where
1579    K: Eq + Hash + Copy,
1580    S: Store<(GuildId, K), V>,
1581{
1582    if let Some(entries) = entries {
1583        entries.remove_parent(guild_id);
1584    }
1585}
1586
1587/// Sets the guild of a guild channel (Discord omits it in `GUILD_CREATE`).
1588const fn set_guild_id(channel: &mut Channel, guild_id: GuildId) {
1589    let slot = match channel {
1590        Channel::Text(channel) | Channel::Announcement(channel) => &mut channel.guild_id,
1591        Channel::Voice(channel) | Channel::Stage(channel) => &mut channel.guild_id,
1592        Channel::Category(channel) => &mut channel.guild_id,
1593        Channel::AnnouncementThread(channel)
1594        | Channel::PublicThread(channel)
1595        | Channel::PrivateThread(channel) => &mut channel.guild_id,
1596        Channel::Directory(channel) => &mut channel.guild_id,
1597        Channel::Forum(channel) | Channel::Media(channel) => &mut channel.guild_id,
1598        Channel::Unknown(channel) => &mut channel.guild_id,
1599        _ => return,
1600    };
1601    *slot = Some(guild_id);
1602}
1603
1604/// Sets the last pin time of a channel that has one; returns whether it has.
1605/// Sets a thread's member count; `false` if `channel` is not a thread.
1606const fn set_member_count(channel: &mut Channel, count: u32) -> bool {
1607    match channel {
1608        Channel::AnnouncementThread(thread)
1609        | Channel::PublicThread(thread)
1610        | Channel::PrivateThread(thread) => {
1611            thread.member_count = Some(count);
1612            true
1613        }
1614        _ => false,
1615    }
1616}
1617
1618const fn set_last_pin_timestamp(channel: &mut Channel, timestamp: Option<Timestamp>) -> bool {
1619    let slot = match channel {
1620        Channel::Text(channel) | Channel::Announcement(channel) => &mut channel.last_pin_timestamp,
1621        Channel::Dm(channel) => &mut channel.last_pin_timestamp,
1622        Channel::GroupDm(channel) => &mut channel.last_pin_timestamp,
1623        Channel::AnnouncementThread(channel)
1624        | Channel::PublicThread(channel)
1625        | Channel::PrivateThread(channel) => &mut channel.last_pin_timestamp,
1626        _ => return false,
1627    };
1628    *slot = timestamp;
1629    true
1630}
1631
1632/// The cache is shared between shards.
1633const _: () = {
1634    const fn assert_send_sync<T: Send + Sync>() {}
1635    assert_send_sync::<Cache>();
1636};