Skip to main content

babyrite/
cache.rs

1//! Cache module for guild channels.
2//!
3//! This module provides caching functionality for guild channels and roles using moka cache.
4//! It includes three caches:
5//! - [`GUILD_CHANNEL_LIST_CACHE`]: Caches the list of channels for each guild.
6//! - [`GUILD_CHANNEL_CACHE`]: Caches individual guild channels.
7//! - [`GUILD_ROLE_CACHE`]: Caches the permissions of each role in a guild.
8//!
9//! The [`CacheArgs`] struct is used to retrieve channels from the cache or fetch them from the API if not found.
10
11use anyhow::Context as _;
12use moka::future::{Cache, CacheBuilder};
13use moka::ops::compute::Op;
14use std::collections::HashMap;
15use std::sync::{LazyLock, Mutex, PoisonError};
16use twilight_http::Client;
17use twilight_model::channel::Channel;
18use twilight_model::guild::Permissions;
19use twilight_model::id::{
20    Id,
21    marker::{ChannelMarker, GuildMarker, RoleMarker},
22};
23
24/// Arguments for cache operations.
25pub struct CacheArgs {
26    /// The ID of the guild.
27    pub guild_id: Id<GuildMarker>,
28    /// The ID of the channel.
29    pub channel_id: Id<ChannelMarker>,
30}
31
32/// Builds a cache with the shared tuning for every cache in this module:
33/// 500 entries, TTL 1 hour, TTI 1 hour.
34///
35/// The time-to-live is not just a memory bound: a cached [`Channel`] carries
36/// the permission overwrites that decide whether a link may be expanded, so a
37/// stale entry keeps authorizing against permissions that no longer exist.
38/// [`invalidate_channel`] drops entries as soon as Discord reports a change, and
39/// this bounds how long a change that never reached us — a missed event across a
40/// gateway session it could not resume — can stay in effect.
41fn bounded_cache<K, V>(name: &str) -> Cache<K, V>
42where
43    K: std::hash::Hash + Eq + Send + Sync + 'static,
44    V: Clone + Send + Sync + 'static,
45{
46    CacheBuilder::new(500)
47        .name(name)
48        .time_to_idle(std::time::Duration::from_secs(3600))
49        .time_to_live(std::time::Duration::from_secs(3600))
50        .build()
51}
52
53/// Every channel of a guild, by ID.
54pub type ChannelMap = HashMap<Id<ChannelMarker>, Channel>;
55
56/// The base permissions of every role in a guild, by ID.
57pub type RolePermissions = HashMap<Id<RoleMarker>, Permissions>;
58
59/// Channel data together with the generation of its guild it was read under.
60///
61/// See [`GUILD_CHANNEL_GENERATIONS`] for why cached channels carry this.
62#[derive(Clone)]
63pub struct Stamped<V> {
64    generation: u64,
65    value: V,
66}
67
68impl<V> Stamped<V> {
69    /// Returns `true` when no channel change in `guild_id` has been reported
70    /// since this value was read.
71    fn is_current(&self, guild_id: Id<GuildMarker>) -> bool {
72        self.generation == channel_generation(guild_id)
73    }
74}
75
76/// Cache for guild channel lists, mapping guild IDs to their channel lists.
77pub static GUILD_CHANNEL_LIST_CACHE: LazyLock<Cache<Id<GuildMarker>, Stamped<ChannelMap>>> =
78    LazyLock::new(|| bounded_cache("guild_channel_list_cache"));
79
80/// Cache for individual guild channels, mapping channel IDs to their channel data.
81pub static GUILD_CHANNEL_CACHE: LazyLock<Cache<Id<ChannelMarker>, Stamped<Channel>>> =
82    LazyLock::new(|| bounded_cache("guild_channel_cache"));
83
84/// How many channel changes Discord has reported for each guild.
85///
86/// Why not rely on dropping cache entries alone: a lookup already in flight
87/// when a change is reported inserts what it read afterwards, and the cache
88/// cannot tell that apart from fresh data. Cached channels instead record the
89/// generation from before they were read, and only the current generation's
90/// are served.
91///
92/// Why entries are never removed: a counter restarting from zero would make
93/// data read under the earlier zero look current again.
94static GUILD_CHANNEL_GENERATIONS: LazyLock<Mutex<HashMap<Id<GuildMarker>, u64>>> =
95    LazyLock::new(|| Mutex::new(HashMap::new()));
96
97fn channel_generation(guild_id: Id<GuildMarker>) -> u64 {
98    GUILD_CHANNEL_GENERATIONS
99        .lock()
100        .unwrap_or_else(PoisonError::into_inner)
101        .get(&guild_id)
102        .copied()
103        .unwrap_or_default()
104}
105
106fn advance_channel_generation(guild_id: Id<GuildMarker>) {
107    *GUILD_CHANNEL_GENERATIONS
108        .lock()
109        .unwrap_or_else(PoisonError::into_inner)
110        .entry(guild_id)
111        .or_default() += 1;
112}
113
114/// Cache for role permissions, mapping guild IDs to each role's base permissions.
115pub static GUILD_ROLE_CACHE: LazyLock<Cache<Id<GuildMarker>, RolePermissions>> =
116    LazyLock::new(|| bounded_cache("guild_role_cache"));
117
118/// Returns `true` when a channel resolved from cache is really in `guild_id`.
119fn belongs_to_guild(channel: &Channel, guild_id: Id<GuildMarker>) -> bool {
120    channel.guild_id == Some(guild_id)
121}
122
123/// Drops every cached view of `channel_id`.
124///
125/// Both caches hold permission overwrites, and those decide whether a linked
126/// channel may be expanded. Serving them after Discord has changed them means
127/// authorizing against permissions that no longer exist — a channel made private
128/// would keep being treated as public. Callers invoke this from the gateway
129/// events that report such a change.
130///
131/// The whole guild's channel list goes too, not just the one entry: the list is a
132/// single cached value holding every channel's overwrites, so there is no way to
133/// replace one member of it.
134///
135/// The guild's generation advances before anything is dropped. That, not the
136/// dropping, is what keeps data read before this call from being served again,
137/// including what a lookup still in flight inserts afterwards.
138pub async fn invalidate_channel(guild_id: Id<GuildMarker>, channel_id: Id<ChannelMarker>) {
139    advance_channel_generation(guild_id);
140    GUILD_CHANNEL_CACHE.invalidate(&channel_id).await;
141    GUILD_CHANNEL_LIST_CACHE.invalidate(&guild_id).await;
142    tracing::debug!(%guild_id, %channel_id, "invalidated channel caches");
143}
144
145/// Returns the base permissions of every role in `guild_id`, from cache or the
146/// Discord API.
147///
148/// These are the other input of the visibility check besides the permission
149/// overwrites, so they are bounded by the same TTL and dropped by
150/// [`invalidate_guild_roles`] when Discord reports a change.
151#[tracing::instrument(skip_all, fields(%guild_id))]
152pub async fn role_permissions(
153    http: &Client,
154    guild_id: Id<GuildMarker>,
155) -> anyhow::Result<RolePermissions> {
156    GUILD_ROLE_CACHE
157        .try_get_with(guild_id, async {
158            tracing::debug!("fetching roles from Discord API");
159            let roles = http.roles(guild_id).await?.models().await?;
160            anyhow::Ok(
161                roles
162                    .into_iter()
163                    .map(|role| (role.id, role.permissions))
164                    .collect(),
165            )
166        })
167        .await
168        .map_err(|e| anyhow::anyhow!("Failed to get roles: {e}"))
169}
170
171/// Drops the cached role permissions of `guild_id`.
172///
173/// A role whose permissions changed would otherwise keep deciding visibility
174/// with what it used to be allowed, just as a stale overwrite would (see
175/// [`invalidate_channel`]). Callers invoke this from the role events and from
176/// `GUILD_CREATE`, which is what a guild looks like again after a reconnect
177/// that may have missed role events.
178pub async fn invalidate_guild_roles(guild_id: Id<GuildMarker>) {
179    GUILD_ROLE_CACHE.invalidate(&guild_id).await;
180    tracing::debug!(%guild_id, "invalidated role cache");
181}
182
183impl CacheArgs {
184    /// Retrieves a guild channel from cache or fetches it from the API.
185    ///
186    /// The returned channel is always in [`Self::guild_id`]. [`GUILD_CHANNEL_CACHE`]
187    /// is keyed by channel id alone, so a hit is verified against the requested
188    /// guild before it is returned; the remaining steps are already scoped to the
189    /// guild.
190    ///
191    /// The result is only as fresh as the cache. [`invalidate_channel`] drops
192    /// entries when Discord reports a change and nothing survives the hour
193    /// regardless, but permission overwrites read from here can still lag a change
194    /// whose event never reached the bot.
195    ///
196    /// The lookup order is:
197    /// 1. Individual channel cache
198    /// 2. Guild channel list cache
199    /// 3. Discord API (with cache update)
200    #[tracing::instrument(
201        skip(self, http),
202        fields(guild_id = %self.guild_id, channel_id = %self.channel_id)
203    )]
204    pub async fn get(&self, http: &Client) -> anyhow::Result<Channel> {
205        if let Some(channel) = self.cached().await? {
206            tracing::debug!("channel cache hit");
207            return Ok(channel);
208        }
209        tracing::debug!("channel cache miss");
210
211        let channel_list = self.channel_list(http).await?;
212
213        let channel = match channel_list.value.get(&self.channel_id).cloned() {
214            Some(c) => c,
215            None => {
216                // Not in the channel list — it may be an active thread,
217                // which is not returned by the guild channels endpoint.
218                tracing::debug!("channel not in list, searching active threads");
219                let data = http
220                    .active_threads(self.guild_id)
221                    .await
222                    .context("Failed to get active threads")?
223                    .model()
224                    .await
225                    .context("Failed to get active threads")?;
226                data.threads
227                    .iter()
228                    .find(|t| t.id == self.channel_id)
229                    .cloned()
230                    .ok_or_else(|| {
231                        tracing::debug!("channel not found in guild or active threads");
232                        anyhow::anyhow!("Channel not found in cache")
233                    })?
234            }
235        };
236
237        // Why not the current generation: the channel is no newer than the list
238        // it was resolved alongside, and a change reported since that list was
239        // read must leave this entry stale even though it is inserted later.
240        GUILD_CHANNEL_CACHE
241            .insert(
242                self.channel_id,
243                Stamped {
244                    generation: channel_list.generation,
245                    value: channel.clone(),
246                },
247            )
248            .await;
249        tracing::trace!("inserted channel into cache");
250        Ok(channel)
251    }
252
253    /// Returns the cached channel, or `None` when nothing is cached for it or
254    /// what is cached was read before the latest channel change in the guild.
255    async fn cached(&self) -> anyhow::Result<Option<Channel>> {
256        let Some(cached) = GUILD_CHANNEL_CACHE.get(&self.channel_id).await else {
257            return Ok(None);
258        };
259        // Channel ids are globally unique snowflakes, so a hit for another
260        // guild is not a stale entry to refresh — the caller asked for a
261        // channel that is not in the guild it named. Refuse rather than
262        // return it: the result feeds visibility checks whose role data is
263        // guild-local and would silently compare against the wrong guild.
264        if !belongs_to_guild(&cached.value, self.guild_id) {
265            tracing::warn!(
266                cached_guild_id = ?cached.value.guild_id,
267                "channel cache hit belongs to another guild"
268            );
269            anyhow::bail!("Channel does not belong to the requested guild");
270        }
271        if !cached.is_current(self.guild_id) {
272            tracing::debug!("cached channel predates a reported channel change");
273            return Ok(None);
274        }
275        Ok(Some(cached.value))
276    }
277
278    /// Returns the guild's channel list from cache, or from the Discord API when
279    /// none is cached or the cached one predates a reported channel change.
280    async fn channel_list(&self, http: &Client) -> anyhow::Result<Stamped<ChannelMap>> {
281        // Lookups on the same key run one at a time, so concurrent misses from
282        // `join_all`-ed link expansions wait for the first fetch and find its
283        // result current instead of each firing an identical `channels` request.
284        GUILD_CHANNEL_LIST_CACHE
285            .entry(self.guild_id)
286            .and_try_compute_with(|cached| async move {
287                if cached.is_some_and(|entry| entry.value().is_current(self.guild_id)) {
288                    return anyhow::Ok(Op::Nop);
289                }
290                let generation = channel_generation(self.guild_id);
291                let channels = self.get_channel_list_from_api(http).await?;
292                anyhow::Ok(Op::Put(Stamped {
293                    generation,
294                    value: channels,
295                }))
296            })
297            .await?
298            .into_entry()
299            .map(|entry| entry.into_value())
300            .context("Failed to get channel list")
301    }
302
303    /// Fetches the channel list from the Discord API.
304    ///
305    /// [`Self::channel_list`] stamps the result and inserts it into
306    /// [`GUILD_CHANNEL_LIST_CACHE`], so this does not touch the cache itself.
307    #[tracing::instrument(skip(self, http), fields(guild_id = %self.guild_id))]
308    async fn get_channel_list_from_api(&self, http: &Client) -> anyhow::Result<ChannelMap> {
309        tracing::debug!("fetching channel list from Discord API");
310        let started = std::time::Instant::now();
311        let channels: HashMap<_, _> = http
312            .guild_channels(self.guild_id)
313            .await
314            .context("Failed to get channel list")?
315            .models()
316            .await
317            .context("Failed to get channel list")?
318            .into_iter()
319            .map(|channel| (channel.id, channel))
320            .collect();
321
322        tracing::debug!(
323            channels = channels.len(),
324            elapsed_ms = started.elapsed().as_millis(),
325            "fetched channel list from Discord API"
326        );
327
328        Ok(channels)
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    // `Channel` has no `Default` and dozens of fields, so build it from JSON.
337    fn channel_in(guild_id: Id<GuildMarker>) -> Channel {
338        serde_json::from_value(serde_json::json!({
339            "id": "1",
340            "type": 0,
341            "guild_id": guild_id.to_string(),
342        }))
343        .unwrap()
344    }
345
346    // Stamps `value` as if it had just been read from Discord.
347    fn read_now<V>(guild_id: Id<GuildMarker>, value: V) -> Stamped<V> {
348        Stamped {
349            generation: channel_generation(guild_id),
350            value,
351        }
352    }
353
354    #[test]
355    fn channel_from_the_requested_guild_is_accepted() {
356        let guild = Id::new(1);
357        assert!(belongs_to_guild(&channel_in(guild), guild));
358    }
359
360    #[test]
361    fn channel_from_another_guild_is_rejected() {
362        assert!(!belongs_to_guild(&channel_in(Id::new(2)), Id::new(1)));
363    }
364
365    // The caches are process-wide statics, so each async test claims ids of its
366    // own rather than relying on ordering or isolation between tests.
367
368    #[tokio::test]
369    async fn invalidating_drops_the_individual_channel() {
370        let guild = Id::new(900);
371        let channel = Id::new(901);
372        GUILD_CHANNEL_CACHE
373            .insert(channel, read_now(guild, channel_in(guild)))
374            .await;
375
376        invalidate_channel(guild, channel).await;
377
378        assert!(GUILD_CHANNEL_CACHE.get(&channel).await.is_none());
379    }
380
381    #[tokio::test]
382    async fn invalidating_drops_the_whole_guild_channel_list() {
383        let guild = Id::new(910);
384        let channel = Id::new(911);
385        let other = Id::new(912);
386        // The list is one cached value covering every channel in the guild, so a
387        // change to one of them has to discard all of it.
388        let mut list = HashMap::new();
389        list.insert(channel, channel_in(guild));
390        list.insert(other, channel_in(guild));
391        GUILD_CHANNEL_LIST_CACHE
392            .insert(guild, read_now(guild, list))
393            .await;
394
395        invalidate_channel(guild, channel).await;
396
397        assert!(GUILD_CHANNEL_LIST_CACHE.get(&guild).await.is_none());
398    }
399
400    #[tokio::test]
401    async fn invalidating_leaves_other_guilds_alone() {
402        let target = Id::new(920);
403        let bystander = Id::new(921);
404        let bystander_channel = Id::new(922);
405        GUILD_CHANNEL_LIST_CACHE
406            .insert(bystander, read_now(bystander, HashMap::new()))
407            .await;
408        GUILD_CHANNEL_CACHE
409            .insert(
410                bystander_channel,
411                read_now(bystander, channel_in(bystander)),
412            )
413            .await;
414
415        invalidate_channel(target, Id::new(923)).await;
416
417        assert!(GUILD_CHANNEL_LIST_CACHE.get(&bystander).await.is_some());
418        assert!(GUILD_CHANNEL_CACHE.get(&bystander_channel).await.is_some());
419    }
420
421    #[tokio::test]
422    async fn channel_read_before_invalidation_is_not_served_even_if_cached_after_it() {
423        let guild = Id::new(940);
424        let channel = Id::new(941);
425        let read_before = read_now(guild, channel_in(guild));
426
427        invalidate_channel(guild, channel).await;
428        // A lookup in flight across the invalidation inserts once it is over.
429        GUILD_CHANNEL_CACHE.insert(channel, read_before).await;
430
431        let lookup = CacheArgs {
432            guild_id: guild,
433            channel_id: channel,
434        };
435        assert!(lookup.cached().await.unwrap().is_none());
436    }
437
438    #[tokio::test]
439    async fn channel_read_after_invalidation_is_served() {
440        let guild = Id::new(950);
441        let channel = Id::new(951);
442
443        invalidate_channel(guild, channel).await;
444        GUILD_CHANNEL_CACHE
445            .insert(channel, read_now(guild, channel_in(guild)))
446            .await;
447
448        let lookup = CacheArgs {
449            guild_id: guild,
450            channel_id: channel,
451        };
452        assert!(lookup.cached().await.unwrap().is_some());
453    }
454
455    #[tokio::test]
456    async fn channel_list_read_before_invalidation_is_not_current() {
457        let guild = Id::new(960);
458        let read_before = read_now(guild, ChannelMap::new());
459
460        invalidate_channel(guild, Id::new(961)).await;
461
462        assert!(!read_before.is_current(guild));
463    }
464
465    #[tokio::test]
466    async fn invalidating_keeps_other_guilds_reads_current() {
467        let target = Id::new(970);
468        let bystander = Id::new(971);
469        let bystander_list = read_now(bystander, ChannelMap::new());
470
471        invalidate_channel(target, Id::new(972)).await;
472
473        assert!(bystander_list.is_current(bystander));
474    }
475
476    #[test]
477    fn channel_without_guild_is_rejected() {
478        let channel: Channel =
479            serde_json::from_value(serde_json::json!({"id": "1", "type": 1})).unwrap();
480        assert!(!belongs_to_guild(&channel, Id::new(1)));
481    }
482
483    #[tokio::test]
484    async fn invalidating_guild_roles_drops_only_that_guild() {
485        let target = Id::new(930);
486        let bystander = Id::new(931);
487        GUILD_ROLE_CACHE.insert(target, HashMap::new()).await;
488        GUILD_ROLE_CACHE.insert(bystander, HashMap::new()).await;
489
490        invalidate_guild_roles(target).await;
491
492        assert!(GUILD_ROLE_CACHE.get(&target).await.is_none());
493        assert!(GUILD_ROLE_CACHE.get(&bystander).await.is_some());
494    }
495}