Skip to main content

Cache

Struct Cache 

Source
pub struct Cache<B: Backend = DashMapBackend> { /* private fields */ }
Expand description

An in-memory view of Discord state, kept up to date from gateway events.

What it keeps is set by its CacheConfig (by default guilds, channels, roles and the current user, D-152); where it keeps it by its Backend (by default DashMapBackend). Feed it every dispatch event with update or update_dispatch, and read it through the per-resource views (guilds, members, …).

Reads return Arcs, which hold no lock and can be kept across .await (D-151). The cache is Send + Sync: share one between all shards, for example in an Arc.

discord.js counterpart: the cache collections of the client’s managers (client.guilds.cache, guild.members.cache, …), filled by the client’s event handlers.

§Examples

use djs_cache::{Cache, CacheConfig, Limit};
use djs_model::{gateway::payload::GuildRoleCreate, id::GuildId};

let cache = Cache::with_config(CacheConfig::builder().members(Limit::Max(1_000)).build());

// `event` is a `GUILD_ROLE_CREATE` received from the gateway.
let previous = cache.update(&event);
assert!(previous.is_none());

let role = cache.roles(GuildId::new(1)).get(event.role.id).unwrap();
assert_eq!(role.name, "mods");

Implementations§

Source§

impl Cache

Source

pub fn new() -> Self

Creates a cache with the default configuration and the DashMapBackend.

discord.js counterpart: the caches new Client() creates (ClientOptions#makeCache).

Source

pub fn with_config(config: CacheConfig) -> Self

Creates a cache with config and the DashMapBackend.

discord.js counterpart: the makeCache option of ClientOptions, with Options.cacheWithLimits.

Source§

impl<B: Backend> Cache<B>

Source

pub fn with_backend(config: CacheConfig, backend: B) -> Self

Creates a cache with config, keeping its resources in stores created by backend.

Backend::store is called once for each enabled resource.

discord.js counterpart: the makeCache option of ClientOptions.

Source

pub const fn config(&self) -> &CacheConfig

Returns the configuration.

discord.js counterpart: the makeCache option of ClientOptions.

Source

pub const fn backend(&self) -> &B

Returns the backend.

discord.js counterpart: none (discord.js caches in Collections).

Source

pub fn update<E: UpdateCache>(&self, event: &E) -> E::Previous

Applies a dispatch event’s payload to the cache, returning the previous state of what it changed (D-153, D-163). See UpdateCache for the events and what each returns.

discord.js counterpart: the client’s internal event handlers (client.actions).

Source

pub fn update_dispatch(&self, event: &DispatchEvent) -> Previous

Applies any dispatch event to the cache, returning the previous state as a Previous. Events the cache does not use return Previous::None.

discord.js counterpart: none (discord.js’ managers update their caches inside the client).

Source

pub fn current_user(&self) -> Option<Arc<CurrentUser>>

Returns the bot’s own user, from READY and USER_UPDATE. Always kept.

discord.js counterpart: client.user.

Source

pub fn unavailable_guilds(&self) -> Vec<GuildId> ⓘ

Returns the guilds that are unavailable: listed in READY but not loaded yet, or unreachable because of a Discord outage. Their cached data, if any, is kept.

discord.js counterpart: guilds with Guild#available === false.

Source

pub fn guilds(&self) -> CacheView<'_, GuildId, CachedGuild, B>

Returns the guilds (Resource::Guild).

discord.js counterpart: client.guilds.cache.

Source

pub fn channels(&self) -> CacheView<'_, ChannelId, Channel, B>

Returns the channels (Resource::Channel); CacheView::in_guild lists a guild’s.

discord.js counterpart: client.channels.cache.

Source

pub fn users(&self) -> CacheView<'_, UserId, CachedUser, B>

Returns the users (Resource::User).

discord.js counterpart: client.users.cache.

Source

pub fn roles(&self, guild_id: GuildId) -> GuildView<'_, RoleId, Role, B>

Returns a guild’s roles (Resource::Role).

discord.js counterpart: guild.roles.cache.

Source

pub fn emojis(&self, guild_id: GuildId) -> GuildView<'_, EmojiId, Emoji, B>

Returns a guild’s custom emojis (Resource::Emoji).

discord.js counterpart: guild.emojis.cache.

Source

pub fn stickers( &self, guild_id: GuildId, ) -> GuildView<'_, StickerId, Sticker, B>

Returns a guild’s stickers (Resource::Sticker).

discord.js counterpart: guild.stickers.cache.

Source

pub fn members( &self, guild_id: GuildId, ) -> GuildView<'_, UserId, CachedMember, B>

Returns a guild’s members (Resource::Member), by user ID.

discord.js counterpart: guild.members.cache.

Source

pub fn threads(&self, guild_id: GuildId) -> GuildView<'_, ChannelId, Channel, B>

Returns a guild’s threads (Resource::Thread).

discord.js counterpart: guild.channels.cache (threads are channels there).

Source

pub fn messages( &self, channel_id: ChannelId, ) -> ChannelView<'_, MessageId, CachedMessage, B>

Returns a channel’s (or thread’s) messages (Resource::Message).

discord.js counterpart: channel.messages.cache.

Source

pub fn presences( &self, guild_id: GuildId, ) -> GuildView<'_, UserId, CachedPresence, B>

Returns a guild’s presences (Resource::Presence), by user ID.

discord.js counterpart: guild.presences.cache.

Source

pub fn voice_states( &self, guild_id: GuildId, ) -> GuildView<'_, UserId, VoiceState, B>

Returns a guild’s voice states (Resource::VoiceState), by user ID. Their member is always None: members are a resource of their own.

discord.js counterpart: guild.voiceStates.cache.

Source

pub fn scheduled_events( &self, guild_id: GuildId, ) -> GuildView<'_, ScheduledEventId, GuildScheduledEvent, B>

Returns a guild’s scheduled events (Resource::ScheduledEvent).

discord.js counterpart: guild.scheduledEvents.cache.

Source

pub fn stage_instances( &self, guild_id: GuildId, ) -> GuildView<'_, StageInstanceId, StageInstance, B>

Returns a guild’s stage instances (Resource::StageInstance).

discord.js counterpart: guild.stageInstances.cache.

Source

pub fn soundboard_sounds( &self, guild_id: GuildId, ) -> GuildView<'_, SoundboardSoundId, SoundboardSound, B>

Returns a guild’s soundboard sounds (Resource::SoundboardSound).

discord.js counterpart: guild.soundboardSounds.cache.

Source§

impl<B: Backend> Cache<B>

Sweeping (D-167, D-168): each method removes the entries its filter returns true for and returns how many it removed. Resources kept per guild or channel pass the guild or channel to the filter. Removing a guild, channel or thread this way also drops what belongs to it, as deleting it does.

discord.js counterpart: client.sweepers.sweepGuilds(filter), sweepUsers(filter), ….

§Examples

use djs_cache::{Cache, CacheConfig, Limit};

let cache = Cache::with_config(CacheConfig::builder().users(Limit::Unlimited).build());
// Forget every bot user.
let swept = cache.sweep_users(|user| user.bot);
assert_eq!(swept, 0);
Source

pub fn sweep_guilds(&self, filter: impl FnMut(&CachedGuild) -> bool) -> usize

Sweeps guilds, with everything in them.

discord.js counterpart: none (discord.js does not sweep guilds).

Source

pub fn sweep_channels(&self, filter: impl FnMut(&Channel) -> bool) -> usize

Sweeps channels, with their messages.

discord.js counterpart: none (discord.js does not sweep channels).

Source

pub fn sweep_users(&self, filter: impl FnMut(&CachedUser) -> bool) -> usize

Sweeps users. Members keep their own reference to their user.

discord.js counterpart: Sweepers#sweepUsers.

Source

pub fn sweep_threads( &self, filter: impl FnMut(GuildId, &Channel) -> bool, ) -> usize

Sweeps threads, with their messages.

discord.js counterpart: Sweepers#sweepThreads.

Source

pub fn sweep_archived_threads(&self, lifetime: Duration) -> usize

Sweeps threads archived more than lifetime ago.

discord.js counterpart: the default threads sweeper (Sweepers.archivedThreadSweepFilter(lifetime)).

Source

pub fn sweep_messages( &self, filter: impl FnMut(ChannelId, &CachedMessage) -> bool, ) -> usize

Sweeps messages.

discord.js counterpart: Sweepers#sweepMessages.

Source

pub fn sweep_messages_older_than(&self, lifetime: Duration) -> usize

Sweeps messages last edited (or, if never edited, sent) more than lifetime ago.

discord.js counterpart: Sweepers.filterByLifetime for messages, which also compares the edit time first.

Source§

impl<B: Backend> Cache<B>

Source

pub fn sweep_roles(&self, filter: impl FnMut(GuildId, &Role) -> bool) -> usize

Sweeps roles.

Source

pub fn sweep_emojis(&self, filter: impl FnMut(GuildId, &Emoji) -> bool) -> usize

Sweeps custom emojis.

Source

pub fn sweep_stickers( &self, filter: impl FnMut(GuildId, &Sticker) -> bool, ) -> usize

Sweeps stickers.

Source

pub fn sweep_members( &self, filter: impl FnMut(GuildId, &CachedMember) -> bool, ) -> usize

Sweeps members.

Source

pub fn sweep_presences( &self, filter: impl FnMut(GuildId, &CachedPresence) -> bool, ) -> usize

Sweeps presences.

Source

pub fn sweep_voice_states( &self, filter: impl FnMut(GuildId, &VoiceState) -> bool, ) -> usize

Sweeps voice states.

Source

pub fn sweep_scheduled_events( &self, filter: impl FnMut(GuildId, &GuildScheduledEvent) -> bool, ) -> usize

Sweeps scheduled events.

Source

pub fn sweep_stage_instances( &self, filter: impl FnMut(GuildId, &StageInstance) -> bool, ) -> usize

Sweeps stage instances.

Source

pub fn sweep_soundboard_sounds( &self, filter: impl FnMut(GuildId, &SoundboardSound) -> bool, ) -> usize

Sweeps soundboard sounds.

Source§

impl<B: Backend> Cache<B>

Storing objects received from the REST API (D-230): each method converts the object to the form the cache keeps, stores it when its resource is enabled, and returns it — so the djs-rs managers hand out the same type whether a value came from the cache or from Discord (D-233).

Source

pub fn store_user(&self, user: &User) -> Arc<CachedUser> ⓘ

Stores a user, for example from Get User, and returns it as cached.

With Resource::User enabled, an equal cached user is reused, so a user stays stored once.

discord.js counterpart: what UserManager#fetch adds to the cache.

§Examples
let cache = Cache::with_config(CacheConfig::builder().users(Limit::Unlimited).build());
let cached = cache.store_user(&user);
assert_eq!(cached.username, "nelly");
assert!(cache.users().get(user.id).is_some());
Source

pub fn store_member( &self, guild_id: GuildId, member: &Member, ) -> Arc<CachedMember> ⓘ

Stores a member of guild_id, for example from Get Guild Member, and returns it as cached (Resource::Member; its user is stored as by store_user).

Unlike GUILD_MEMBER_ADD, this does not count a join in the guild’s member count.

discord.js counterpart: what GuildMemberManager#fetch adds to the cache.

Source

pub fn store_message(&self, message: &Message) -> Arc<CachedMessage> ⓘ

Stores a message, for example from Get Channel Message or Create Message, and returns it as cached (Resource::Message; its author and member as for MESSAGE_CREATE).

discord.js counterpart: what MessageManager#fetch adds to the cache.

Source

pub fn store_channel(&self, channel: &Channel) -> Arc<Channel> ⓘ

Stores a channel or thread, for example from Get Channel, and returns it as cached (Resource::Channel, or Resource::Thread for a thread in a guild).

discord.js counterpart: what ChannelManager#fetch adds to the cache.

Source

pub fn store_role(&self, guild_id: GuildId, role: &Role) -> Arc<Role> ⓘ

Stores a role of guild_id, for example from Get Guild Role, and returns it as cached (Resource::Role).

discord.js counterpart: what RoleManager#fetch adds to the cache.

Source

pub fn store_emoji(&self, guild_id: GuildId, emoji: &Emoji) -> Arc<Emoji> ⓘ

Stores a custom emoji of guild_id, for example from Get Guild Emoji, and returns it as cached (Resource::Emoji).

discord.js counterpart: what GuildEmojiManager#fetch adds to the cache.

Source

pub fn store_sticker( &self, guild_id: GuildId, sticker: &Sticker, ) -> Arc<Sticker> ⓘ

Stores a sticker of guild_id, for example from Get Guild Sticker, and returns it as cached (Resource::Sticker).

discord.js counterpart: what GuildStickerManager#fetch adds to the cache.

Source

pub fn store_scheduled_event( &self, guild_id: GuildId, event: &GuildScheduledEvent, ) -> Arc<GuildScheduledEvent> ⓘ

Stores a scheduled event of guild_id, for example from Get Guild Scheduled Event, and returns it as cached (Resource::ScheduledEvent).

discord.js counterpart: what GuildScheduledEventManager#fetch adds to the cache.

Source

pub fn store_stage_instance( &self, guild_id: GuildId, stage: &StageInstance, ) -> Arc<StageInstance> ⓘ

Stores a stage instance of guild_id, for example from Get Stage Instance, and returns it as cached (Resource::StageInstance).

discord.js counterpart: what StageInstanceManager#fetch adds to the cache.

Source

pub fn store_soundboard_sound( &self, guild_id: GuildId, sound: &SoundboardSound, ) -> Arc<SoundboardSound> ⓘ

Stores a soundboard sound of guild_id, for example from Get Guild Soundboard Sound, and returns it as cached (Resource::SoundboardSound).

discord.js counterpart: what GuildSoundboardSoundManager#fetch adds to the cache.

Source

pub fn store_guild(&self, guild: &Guild) -> Arc<CachedGuild> ⓘ

Stores a guild, for example from Get Guild, and returns it as cached (Resource::Guild); its roles, emojis and stickers replace the cached ones when sent, as for GUILD_UPDATE.

A guild the cache already holds keeps what only GUILD_CREATE sends (joined_at, large, member_count); a new one takes its member count from approximate_member_count (sent with with_counts), or 0.

discord.js counterpart: what GuildManager#fetch adds to the cache.

Source§

impl<B: Backend> Cache<B>

Permissions computed from the cached guild, roles, member and channel (D-292).

Source

pub fn member_permissions( &self, guild_id: GuildId, user_id: UserId, ) -> Option<Permissions>

The permissions of the member user_id in the guild guild_id, as Discord applies them now: [Permissions::guild_level] from the cached guild owner, @everyone role and the member’s roles, then [Permissions::during_timeout] if the member is timed out (D-294).

None when the cache lacks something the computation needs: the guild, the member, or one of the member’s roles (so enable Resource::Member, which is off by default, and keep Resource::Role). A missing piece never gives a wrong answer.

discord.js counterpart: GuildMember#permissions.

§Examples
use djs_cache::Cache;
use djs_model::{id::{GuildId, UserId}, permissions::Permissions};

fn can_ban(cache: &Cache, guild: GuildId, user: UserId) -> bool {
    cache
        .member_permissions(guild, user)
        .is_some_and(|permissions| permissions.contains(Permissions::BAN_MEMBERS))
}
Source

pub fn member_permissions_in( &self, channel: &Channel, user_id: UserId, ) -> Option<Permissions>

The permissions of the member user_id in channel (a guild channel or a thread, cached or not), as Discord applies them now: member_permissions before the timeout, then [Permissions::in_channel] with the channel’s overwrites and the implicit denials (D-295), then the timeout (D-294). A thread takes the overwrites of its parent channel, which must be cached.

None for a channel outside a guild, or when the cache lacks something the computation needs (see member_permissions; for a thread, its parent).

discord.js counterpart: GuildMember#permissionsIn(channel) / GuildChannel#permissionsFor(member).

Trait Implementations§

Source§

impl<B: Backend> Debug for Cache<B>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Cache

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<B = DashMapBackend> !Freeze for Cache<B>

§

impl<B = DashMapBackend> !RefUnwindSafe for Cache<B>

§

impl<B> Send for Cache<B>

§

impl<B> Sync for Cache<B>

§

impl<B> Unpin for Cache<B>
where B: Unpin, <B as Backend>::Store<Id<GuildMarker>, CachedGuild>: Unpin, <B as Backend>::Store<Id<ChannelMarker>, Channel>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<RoleMarker>), Role>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<EmojiMarker>), Emoji>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<StickerMarker>), Sticker>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedMember>: Unpin, <B as Backend>::Store<Id<UserMarker>, CachedUser>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<ChannelMarker>), Channel>: Unpin, <B as Backend>::Store<(Id<ChannelMarker>, Id<MessageMarker>), CachedMessage>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedPresence>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), VoiceState>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<ScheduledEventMarker>), GuildScheduledEvent>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<StageInstanceMarker>), StageInstance>: Unpin, <B as Backend>::Store<(Id<GuildMarker>, Id<SoundboardSoundMarker>), SoundboardSound>: Unpin,

§

impl<B> UnsafeUnpin for Cache<B>
where B: UnsafeUnpin, <B as Backend>::Store<Id<GuildMarker>, CachedGuild>: UnsafeUnpin, <B as Backend>::Store<Id<ChannelMarker>, Channel>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<RoleMarker>), Role>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<EmojiMarker>), Emoji>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<StickerMarker>), Sticker>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedMember>: UnsafeUnpin, <B as Backend>::Store<Id<UserMarker>, CachedUser>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<ChannelMarker>), Channel>: UnsafeUnpin, <B as Backend>::Store<(Id<ChannelMarker>, Id<MessageMarker>), CachedMessage>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedPresence>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), VoiceState>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<ScheduledEventMarker>), GuildScheduledEvent>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<StageInstanceMarker>), StageInstance>: UnsafeUnpin, <B as Backend>::Store<(Id<GuildMarker>, Id<SoundboardSoundMarker>), SoundboardSound>: UnsafeUnpin,

§

impl<B> UnwindSafe for Cache<B>
where B: UnwindSafe, <B as Backend>::Store<Id<GuildMarker>, CachedGuild>: UnwindSafe, <B as Backend>::Store<Id<ChannelMarker>, Channel>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<RoleMarker>), Role>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<EmojiMarker>), Emoji>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<StickerMarker>), Sticker>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedMember>: UnwindSafe, <B as Backend>::Store<Id<UserMarker>, CachedUser>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<ChannelMarker>), Channel>: UnwindSafe, <B as Backend>::Store<(Id<ChannelMarker>, Id<MessageMarker>), CachedMessage>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), CachedPresence>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<UserMarker>), VoiceState>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<ScheduledEventMarker>), GuildScheduledEvent>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<StageInstanceMarker>), StageInstance>: UnwindSafe, <B as Backend>::Store<(Id<GuildMarker>, Id<SoundboardSoundMarker>), SoundboardSound>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.