Skip to main content

djs_cache/
update.rs

1//! Applying gateway events to the cache (D-153, D-161, D-163).
2
3use std::sync::Arc;
4
5use djs_model::{
6    channel::Channel,
7    emoji::Emoji,
8    gateway::{
9        DispatchEvent,
10        payload::{
11            ChannelCreate, ChannelDelete, ChannelPinsUpdate, ChannelUpdate, GuildCreate,
12            GuildDelete, GuildEmojisUpdate, GuildMemberAdd, GuildMemberRemove, GuildMemberUpdate,
13            GuildMembersChunk, GuildRoleCreate, GuildRoleDelete, GuildRoleUpdate,
14            GuildScheduledEventCreate, GuildScheduledEventDelete, GuildScheduledEventUpdate,
15            GuildSoundboardSoundCreate, GuildSoundboardSoundDelete, GuildSoundboardSoundUpdate,
16            GuildSoundboardSoundsUpdate, GuildStickersUpdate, GuildUpdate, InteractionCreate,
17            MessageCreate, MessageDelete, MessageDeleteBulk, MessageReactionAdd,
18            MessageReactionRemove, MessageReactionRemoveAll, MessageReactionRemoveEmoji,
19            MessageUpdate, PresenceUpdate, Ready, SoundboardSounds, StageInstanceCreate,
20            StageInstanceDelete, StageInstanceUpdate, ThreadCreate, ThreadDelete, ThreadListSync,
21            ThreadMembersUpdate, ThreadUpdate, TypingStart, UserUpdate, VoiceStateUpdate,
22        },
23    },
24    guild::Role,
25    guild_scheduled_event::GuildScheduledEvent,
26    soundboard::SoundboardSound,
27    stage_instance::StageInstance,
28    sticker::Sticker,
29    user::CurrentUser,
30    voice::VoiceState,
31};
32
33use crate::{
34    Backend, Cache, CachedGuild, CachedMember, CachedMessage, CachedPresence, cache::ReactionChange,
35};
36
37mod sealed {
38    pub trait Sealed {}
39}
40
41/// A gateway event payload the cache can apply, with the type of the previous state it
42/// returns (D-163).
43///
44/// Use it through [`Cache::update`]; for a whole [`DispatchEvent`] use
45/// [`Cache::update_dispatch`]. Every update borrows the event and copies what the cache keeps
46/// (D-161). The previous state is what the event replaced or removed, or nothing when the
47/// resource is disabled or the entry was not cached; for a guild it is the guild itself, not
48/// its roles, channels or members.
49///
50/// | Payload | What it does | `Previous` |
51/// |---|---|---|
52/// | [`Ready`] | sets the current user; lists the guilds as unavailable | `Option<Arc<CurrentUser>>` |
53/// | [`UserUpdate`] | replaces the current user | `Option<Arc<CurrentUser>>` |
54/// | [`GuildCreate`] | caches the guild with its channels, roles, emojis, stickers and members | `Option<Arc<CachedGuild>>` |
55/// | [`GuildUpdate`] | updates the guild (and its roles, emojis, stickers if sent) | `Option<Arc<CachedGuild>>` |
56/// | [`GuildDelete`] | removes the guild and everything in it, or marks it unavailable during an outage | `Option<Arc<CachedGuild>>` |
57/// | [`ChannelCreate`], [`ChannelUpdate`] | caches the channel (threads are skipped) | `Option<Arc<Channel>>` |
58/// | [`ChannelDelete`] | removes the channel | `Option<Arc<Channel>>` |
59/// | [`ChannelPinsUpdate`] | sets the channel's last pin time | `Option<Arc<Channel>>` |
60/// | [`GuildRoleCreate`], [`GuildRoleUpdate`] | caches the role | `Option<Arc<Role>>` |
61/// | [`GuildRoleDelete`] | removes the role | `Option<Arc<Role>>` |
62/// | [`GuildEmojisUpdate`] | replaces the guild's emojis | `Vec<Arc<Emoji>>` |
63/// | [`GuildStickersUpdate`] | replaces the guild's stickers | `Vec<Arc<Sticker>>` |
64/// | [`GuildMemberAdd`] | caches the member, counts it in the guild | `Option<Arc<CachedMember>>` |
65/// | [`GuildMemberUpdate`] | updates (or adds) the member | `Option<Arc<CachedMember>>` |
66/// | [`GuildMemberRemove`] | removes the member, uncounts it | `Option<Arc<CachedMember>>` |
67/// | [`GuildMembersChunk`] | caches the members (and their presences) | `Vec<Arc<CachedMember>>` (those replaced) |
68/// | [`MessageCreate`] | caches the message (author as a user, its member as a member) | `Option<Arc<CachedMessage>>` |
69/// | [`MessageUpdate`] | replaces a cached message | `Option<Arc<CachedMessage>>` |
70/// | [`MessageDelete`] | removes the message | `Option<Arc<CachedMessage>>` |
71/// | [`MessageDeleteBulk`] | removes the messages | `Vec<Arc<CachedMessage>>` |
72/// | [`MessageReactionAdd`], [`MessageReactionRemove`], [`MessageReactionRemoveAll`], [`MessageReactionRemoveEmoji`] | updates a cached message's reactions | `Option<Arc<CachedMessage>>` |
73/// | [`TypingStart`] | caches the typing member (in a guild) | `Option<Arc<CachedMember>>` |
74/// | [`InteractionCreate`] | caches the interaction's user and member, and the resolved users and members (not the resolved partial channels) | `Option<Arc<CachedMember>>` (the interaction's member) |
75/// | [`PresenceUpdate`] | caches the presence, or removes it when offline | `Option<Arc<CachedPresence>>` |
76/// | [`VoiceStateUpdate`] | caches the voice state, or removes it when the user left voice | `Option<Arc<VoiceState>>` |
77/// | [`ThreadCreate`], [`ThreadUpdate`] | caches the thread | `Option<Arc<Channel>>` |
78/// | [`ThreadDelete`] | removes the thread and its messages | `Option<Arc<Channel>>` |
79/// | [`ThreadListSync`] | replaces the synced channels' active threads | `Vec<Arc<Channel>>` |
80/// | [`ThreadMembersUpdate`] | sets the thread's member count; caches the added members as guild members | `Option<Arc<Channel>>` |
81/// | [`GuildScheduledEventCreate`], [`GuildScheduledEventUpdate`], [`GuildScheduledEventDelete`] | caches / removes the event | `Option<Arc<GuildScheduledEvent>>` |
82/// | [`StageInstanceCreate`], [`StageInstanceUpdate`], [`StageInstanceDelete`] | caches / removes the stage instance | `Option<Arc<StageInstance>>` |
83/// | [`GuildSoundboardSoundCreate`], [`GuildSoundboardSoundUpdate`], [`GuildSoundboardSoundDelete`] | caches / removes the sound | `Option<Arc<SoundboardSound>>` |
84/// | [`GuildSoundboardSoundsUpdate`] | caches the sounds | `Vec<Arc<SoundboardSound>>` (those replaced) |
85/// | [`SoundboardSounds`] | replaces the guild's sounds | `Vec<Arc<SoundboardSound>>` |
86///
87/// Users seen in member events are cached too when [`Resource::User`](crate::Resource::User)
88/// is enabled.
89///
90/// This trait is sealed: the cache implements it for the payloads it understands.
91///
92/// discord.js counterpart: the client's internal actions (`client.actions.GuildMemberUpdate`,
93/// …), which also return the old and new state.
94pub trait UpdateCache: sealed::Sealed {
95    /// The previous state this event returns.
96    type Previous;
97
98    /// Applies the event. Called by [`Cache::update`].
99    #[doc(hidden)]
100    fn update_cache<B: Backend>(&self, cache: &Cache<B>) -> Self::Previous;
101}
102
103/// The previous state returned by [`Cache::update_dispatch`]: the
104/// [`UpdateCache::Previous`] of the event, in a variant per kind.
105///
106/// discord.js counterpart: the old values discord.js' events pass (`oldMessage`, `oldMember`, …).
107#[derive(Clone, Debug, PartialEq)]
108#[non_exhaustive]
109pub enum Previous {
110    /// The event changes nothing in the cache, or nothing was cached before it.
111    None,
112    /// The current user before a [`Ready`] or [`UserUpdate`].
113    CurrentUser(Arc<CurrentUser>),
114    /// A guild before a [`GuildCreate`], [`GuildUpdate`] or [`GuildDelete`].
115    Guild(Arc<CachedGuild>),
116    /// A channel before a channel event.
117    Channel(Arc<Channel>),
118    /// A role before a role event.
119    Role(Arc<Role>),
120    /// A guild's emojis before a [`GuildEmojisUpdate`].
121    Emojis(Vec<Arc<Emoji>>),
122    /// A guild's stickers before a [`GuildStickersUpdate`].
123    Stickers(Vec<Arc<Sticker>>),
124    /// A member before a member event.
125    Member(Arc<CachedMember>),
126    /// The members a [`GuildMembersChunk`] replaced.
127    Members(Vec<Arc<CachedMember>>),
128    /// A message before a message or reaction event.
129    Message(Arc<CachedMessage>),
130    /// The messages a [`MessageDeleteBulk`] removed.
131    Messages(Vec<Arc<CachedMessage>>),
132    /// A presence before a [`PresenceUpdate`].
133    Presence(Arc<CachedPresence>),
134    /// A voice state before a [`VoiceStateUpdate`].
135    VoiceState(Arc<VoiceState>),
136    /// A thread before a thread event.
137    Thread(Arc<Channel>),
138    /// The threads a [`ThreadListSync`] replaced.
139    Threads(Vec<Arc<Channel>>),
140    /// A scheduled event before a scheduled event event.
141    ScheduledEvent(Arc<GuildScheduledEvent>),
142    /// A stage instance before a stage instance event.
143    StageInstance(Arc<StageInstance>),
144    /// A soundboard sound before a soundboard sound event.
145    SoundboardSound(Arc<SoundboardSound>),
146    /// The soundboard sounds a [`GuildSoundboardSoundsUpdate`] or [`SoundboardSounds`]
147    /// replaced.
148    SoundboardSounds(Vec<Arc<SoundboardSound>>),
149}
150
151/// Implements [`UpdateCache`] for a payload: `Payload => Previous, |event, cache| body`.
152macro_rules! update_cache {
153    ($($payload:ty => $previous:ty, |$event:ident, $cache:ident| $body:expr;)*) => {$(
154        impl sealed::Sealed for $payload {}
155
156        impl UpdateCache for $payload {
157            type Previous = $previous;
158
159            fn update_cache<B: Backend>(&self, $cache: &Cache<B>) -> $previous {
160                let $event = self;
161                $body
162            }
163        }
164    )*};
165}
166
167update_cache! {
168    Ready => Option<Arc<CurrentUser>>, |event, cache| {
169        for guild in &event.guilds {
170            cache.mark_unavailable(guild.id);
171        }
172        cache.set_current_user(&event.user)
173    };
174    UserUpdate => Option<Arc<CurrentUser>>, |event, cache| cache.set_current_user(event);
175    GuildCreate => Option<Arc<CachedGuild>>, |event, cache| match event {
176        GuildCreate::Available(guild) => cache.insert_guild(guild),
177        GuildCreate::Unavailable(guild) => {
178            cache.mark_unavailable(guild.id);
179            None
180        }
181        _ => None,
182    };
183    GuildUpdate => Option<Arc<CachedGuild>>, |event, cache| cache.update_guild(event);
184    GuildDelete => Option<Arc<CachedGuild>>, |event, cache| {
185        cache.remove_guild(event.id, event.unavailable)
186    };
187    ChannelCreate => Option<Arc<Channel>>, |event, cache| cache.insert_channel(event, None);
188    ChannelUpdate => Option<Arc<Channel>>, |event, cache| cache.insert_channel(event, None);
189    ChannelDelete => Option<Arc<Channel>>, |event, cache| cache.remove_channel(event);
190    ChannelPinsUpdate => Option<Arc<Channel>>, |event, cache| {
191        cache.update_pins(event.channel_id, event.last_pin_timestamp)
192    };
193    GuildRoleCreate => Option<Arc<Role>>, |event, cache| {
194        cache.insert_role(event.guild_id, &event.role)
195    };
196    GuildRoleUpdate => Option<Arc<Role>>, |event, cache| {
197        cache.insert_role(event.guild_id, &event.role)
198    };
199    GuildRoleDelete => Option<Arc<Role>>, |event, cache| {
200        cache.remove_role(event.guild_id, event.role_id)
201    };
202    GuildEmojisUpdate => Vec<Arc<Emoji>>, |event, cache| {
203        cache.replace_emojis(event.guild_id, &event.emojis)
204    };
205    GuildStickersUpdate => Vec<Arc<Sticker>>, |event, cache| {
206        cache.replace_stickers(event.guild_id, &event.stickers)
207    };
208    GuildMemberAdd => Option<Arc<CachedMember>>, |event, cache| {
209        let previous = cache.upsert_member(event.guild_id, event);
210        if previous.is_none() {
211            cache.count_member(event.guild_id, true);
212        }
213        previous
214    };
215    GuildMemberUpdate => Option<Arc<CachedMember>>, |event, cache| cache.update_member(event);
216    GuildMemberRemove => Option<Arc<CachedMember>>, |event, cache| {
217        cache.count_member(event.guild_id, false);
218        cache.remove_member(event.guild_id, &event.user)
219    };
220    GuildMembersChunk => Vec<Arc<CachedMember>>, |event, cache| {
221        for presence in &event.presences {
222            cache.update_presence(event.guild_id, presence);
223        }
224        event
225            .members
226            .iter()
227            .filter_map(|member| cache.upsert_member(event.guild_id, member))
228            .collect()
229    };
230    MessageCreate => Option<Arc<CachedMessage>>, |event, cache| cache.insert_message(event);
231    MessageUpdate => Option<Arc<CachedMessage>>, |event, cache| cache.update_message(event);
232    MessageDelete => Option<Arc<CachedMessage>>, |event, cache| {
233        cache.remove_message(event.channel_id, event.id)
234    };
235    MessageDeleteBulk => Vec<Arc<CachedMessage>>, |event, cache| {
236        event
237            .ids
238            .iter()
239            .filter_map(|&id| cache.remove_message(event.channel_id, id))
240            .collect()
241    };
242    MessageReactionAdd => Option<Arc<CachedMessage>>, |event, cache| {
243        if let (Some(guild_id), Some(member)) = (event.guild_id, &event.member) {
244            cache.upsert_member(guild_id, member);
245        }
246        cache.react(event.channel_id, event.message_id, ReactionChange::Add {
247            emoji: &event.emoji,
248            user_id: event.user_id,
249            burst: event.burst,
250            burst_colors: &event.burst_colors,
251        })
252    };
253    MessageReactionRemove => Option<Arc<CachedMessage>>, |event, cache| {
254        cache.react(event.channel_id, event.message_id, ReactionChange::Remove {
255            emoji: &event.emoji,
256            user_id: event.user_id,
257            burst: event.burst,
258        })
259    };
260    MessageReactionRemoveAll => Option<Arc<CachedMessage>>, |event, cache| {
261        cache.react(event.channel_id, event.message_id, ReactionChange::RemoveAll)
262    };
263    MessageReactionRemoveEmoji => Option<Arc<CachedMessage>>, |event, cache| {
264        cache.react(event.channel_id, event.message_id, ReactionChange::RemoveEmoji(&event.emoji))
265    };
266    TypingStart => Option<Arc<CachedMember>>, |event, cache| {
267        cache.upsert_member(event.guild_id?, event.member.as_deref()?)
268    };
269    InteractionCreate => Option<Arc<CachedMember>>, |event, cache| cache.apply_interaction(event);
270    PresenceUpdate => Option<Arc<CachedPresence>>, |event, cache| {
271        cache.update_presence(event.guild_id?, event)
272    };
273    VoiceStateUpdate => Option<Arc<VoiceState>>, |event, cache| cache.update_voice_state(event);
274    ThreadCreate => Option<Arc<Channel>>, |event, cache| cache.insert_thread(&event.thread);
275    ThreadUpdate => Option<Arc<Channel>>, |event, cache| cache.insert_thread(event);
276    ThreadDelete => Option<Arc<Channel>>, |event, cache| {
277        cache.remove_thread(event.guild_id, event.id)
278    };
279    ThreadListSync => Vec<Arc<Channel>>, |event, cache| {
280        cache.sync_threads(event.guild_id, event.channel_ids.as_deref(), &event.threads)
281    };
282    ThreadMembersUpdate => Option<Arc<Channel>>, |event, cache| cache.update_thread_members(event);
283    GuildScheduledEventCreate => Option<Arc<GuildScheduledEvent>>, |event, cache| {
284        cache.put_scheduled_event(event)
285    };
286    GuildScheduledEventUpdate => Option<Arc<GuildScheduledEvent>>, |event, cache| {
287        cache.put_scheduled_event(event)
288    };
289    GuildScheduledEventDelete => Option<Arc<GuildScheduledEvent>>, |event, cache| {
290        cache.remove_scheduled_event(event)
291    };
292    StageInstanceCreate => Option<Arc<StageInstance>>, |event, cache| {
293        cache.put_stage_instance(event)
294    };
295    StageInstanceUpdate => Option<Arc<StageInstance>>, |event, cache| {
296        cache.put_stage_instance(event)
297    };
298    StageInstanceDelete => Option<Arc<StageInstance>>, |event, cache| {
299        cache.remove_stage_instance(event)
300    };
301    GuildSoundboardSoundCreate => Option<Arc<SoundboardSound>>, |event, cache| {
302        cache.put_soundboard_sound(event.guild_id?, event)
303    };
304    GuildSoundboardSoundUpdate => Option<Arc<SoundboardSound>>, |event, cache| {
305        cache.put_soundboard_sound(event.guild_id?, event)
306    };
307    GuildSoundboardSoundDelete => Option<Arc<SoundboardSound>>, |event, cache| {
308        cache.remove_soundboard_sound(event.guild_id, event.sound_id)
309    };
310    GuildSoundboardSoundsUpdate => Vec<Arc<SoundboardSound>>, |event, cache| {
311        event
312            .soundboard_sounds
313            .iter()
314            .filter_map(|sound| cache.put_soundboard_sound(event.guild_id, sound))
315            .collect()
316    };
317    SoundboardSounds => Vec<Arc<SoundboardSound>>, |event, cache| {
318        cache.replace_soundboard_sounds(event.guild_id, &event.soundboard_sounds)
319    };
320}
321
322/// [`Cache::update_dispatch`].
323pub(crate) fn dispatch<B: Backend>(cache: &Cache<B>, event: &DispatchEvent) -> Previous {
324    match event {
325        DispatchEvent::Ready(event) => cache.update(&**event).map(Previous::CurrentUser).into(),
326        DispatchEvent::UserUpdate(event) => {
327            cache.update(&**event).map(Previous::CurrentUser).into()
328        }
329        DispatchEvent::GuildCreate(event) => cache.update(&**event).map(Previous::Guild).into(),
330        DispatchEvent::GuildUpdate(event) => cache.update(&**event).map(Previous::Guild).into(),
331        DispatchEvent::GuildDelete(event) => cache.update(event).map(Previous::Guild).into(),
332        DispatchEvent::ChannelCreate(event) => cache.update(&**event).map(Previous::Channel).into(),
333        DispatchEvent::ChannelUpdate(event) => cache.update(&**event).map(Previous::Channel).into(),
334        DispatchEvent::ChannelDelete(event) => cache.update(&**event).map(Previous::Channel).into(),
335        DispatchEvent::ChannelPinsUpdate(event) => {
336            cache.update(&**event).map(Previous::Channel).into()
337        }
338        DispatchEvent::GuildRoleCreate(event) => cache.update(&**event).map(Previous::Role).into(),
339        DispatchEvent::GuildRoleUpdate(event) => cache.update(&**event).map(Previous::Role).into(),
340        DispatchEvent::GuildRoleDelete(event) => cache.update(event).map(Previous::Role).into(),
341        DispatchEvent::GuildEmojisUpdate(event) => Previous::Emojis(cache.update(&**event)),
342        DispatchEvent::GuildStickersUpdate(event) => Previous::Stickers(cache.update(&**event)),
343        DispatchEvent::GuildMemberAdd(event) => cache.update(&**event).map(Previous::Member).into(),
344        DispatchEvent::GuildMemberUpdate(event) => {
345            cache.update(&**event).map(Previous::Member).into()
346        }
347        DispatchEvent::GuildMemberRemove(event) => {
348            cache.update(&**event).map(Previous::Member).into()
349        }
350        DispatchEvent::GuildMembersChunk(event) => Previous::Members(cache.update(&**event)),
351        DispatchEvent::MessageCreate(event) => cache.update(&**event).map(Previous::Message).into(),
352        DispatchEvent::MessageUpdate(event) => cache.update(&**event).map(Previous::Message).into(),
353        DispatchEvent::MessageDelete(event) => cache.update(&**event).map(Previous::Message).into(),
354        DispatchEvent::MessageDeleteBulk(event) => Previous::Messages(cache.update(&**event)),
355        DispatchEvent::MessageReactionAdd(event) => {
356            cache.update(&**event).map(Previous::Message).into()
357        }
358        DispatchEvent::MessageReactionRemove(event) => {
359            cache.update(&**event).map(Previous::Message).into()
360        }
361        DispatchEvent::MessageReactionRemoveAll(event) => {
362            cache.update(event).map(Previous::Message).into()
363        }
364        DispatchEvent::MessageReactionRemoveEmoji(event) => {
365            cache.update(&**event).map(Previous::Message).into()
366        }
367        DispatchEvent::PresenceUpdate(event) => {
368            cache.update(&**event).map(Previous::Presence).into()
369        }
370        DispatchEvent::VoiceStateUpdate(event) => {
371            cache.update(&**event).map(Previous::VoiceState).into()
372        }
373        DispatchEvent::ThreadCreate(event) => cache.update(&**event).map(Previous::Thread).into(),
374        DispatchEvent::ThreadUpdate(event) => cache.update(&**event).map(Previous::Thread).into(),
375        DispatchEvent::ThreadDelete(event) => cache.update(&**event).map(Previous::Thread).into(),
376        DispatchEvent::ThreadListSync(event) => Previous::Threads(cache.update(&**event)),
377        DispatchEvent::ThreadMembersUpdate(event) => {
378            cache.update(&**event).map(Previous::Thread).into()
379        }
380        DispatchEvent::TypingStart(event) => cache.update(&**event).map(Previous::Member).into(),
381        DispatchEvent::InteractionCreate(event) => {
382            cache.update(&**event).map(Previous::Member).into()
383        }
384        DispatchEvent::GuildScheduledEventCreate(event) => {
385            cache.update(&**event).map(Previous::ScheduledEvent).into()
386        }
387        DispatchEvent::GuildScheduledEventUpdate(event) => {
388            cache.update(&**event).map(Previous::ScheduledEvent).into()
389        }
390        DispatchEvent::GuildScheduledEventDelete(event) => {
391            cache.update(&**event).map(Previous::ScheduledEvent).into()
392        }
393        DispatchEvent::StageInstanceCreate(event) => {
394            cache.update(&**event).map(Previous::StageInstance).into()
395        }
396        DispatchEvent::StageInstanceUpdate(event) => {
397            cache.update(&**event).map(Previous::StageInstance).into()
398        }
399        DispatchEvent::StageInstanceDelete(event) => {
400            cache.update(&**event).map(Previous::StageInstance).into()
401        }
402        DispatchEvent::GuildSoundboardSoundCreate(event) => {
403            cache.update(&**event).map(Previous::SoundboardSound).into()
404        }
405        DispatchEvent::GuildSoundboardSoundUpdate(event) => {
406            cache.update(&**event).map(Previous::SoundboardSound).into()
407        }
408        DispatchEvent::GuildSoundboardSoundDelete(event) => {
409            cache.update(event).map(Previous::SoundboardSound).into()
410        }
411        DispatchEvent::GuildSoundboardSoundsUpdate(event) => {
412            Previous::SoundboardSounds(cache.update(&**event))
413        }
414        DispatchEvent::SoundboardSounds(event) => {
415            Previous::SoundboardSounds(cache.update(&**event))
416        }
417        _ => Previous::None,
418    }
419}
420
421impl From<Option<Self>> for Previous {
422    fn from(previous: Option<Self>) -> Self {
423        previous.unwrap_or(Self::None)
424    }
425}