Skip to main content

Crate djs_cache

Crate djs_cache 

Source
Expand description

§djs-cache

Configurable, pluggable in-memory cache for Discord entities.

Status: alpha. Every resource is cached from its gateway events (guilds, channels, threads, roles, emojis, stickers, members, users, messages with their reactions, presences, voice states, scheduled events, stage instances, soundboard sounds and the current user) and can be swept; the djs-rs Client keeps one when configured with ClientBuilder::cache. The API may still change between alpha releases; see the changelog.

discord.js counterpart: the caching layer inside discord.js (the managers’ cache collections, the makeCache and sweepers client options)

§Overview

  • What is cached is set per Resource with a Limit in a CacheConfig: Limit::Disabled, Limit::Max or Limit::Unlimited, like discord.js Options.cacheWithLimits.
  • The default is minimal: guilds, channels and roles (and always the current user). CacheConfig::discord_js keeps what discord.js keeps by default: everything, with the latest 200 messages per channel.
  • Limits count where discord.js counts them: per guild for guild resources (members, roles, emojis, presences, …), per channel for messages, over the whole cache for guilds, channels and users. A full scope evicts the entry inserted first.
  • Events go in by reference: Cache::update takes any payload implementing UpdateCache and returns its previous state, typed per event (a member update returns the member before it); Cache::update_dispatch takes a whole DispatchEvent.
  • Reads go through views, like a discord.js manager’s cache: cache.guilds().get(id), cache.members(guild_id).values(), … They return Arcs: cheap to clone, holding no lock, safe to keep across .await.
  • Own types only where needed: roles, emojis, stickers, channels, threads, voice states, scheduled events, stage instances and soundboard sounds are the djs-model types; CachedGuild leaves out the lists kept elsewhere, CachedUser and CachedMember keep their rarely set fields (banners, decorations, boost and timeout times, …) behind one box read through methods, CachedMember and CachedMessage share their CachedUser with the user resource, and CachedPresence keeps only its user’s ID.
  • Sweeping: every resource has a sweep_* method taking a filter (cache.sweep_users(|user| user.bot)), plus two lifetime presets, Cache::sweep_messages_older_than and Cache::sweep_archived_threads. The periodic sweeps of CacheConfig::sweepers (by default discord.js’: threads archived over 4 hours, hourly) are run by the djs-rs Client; the cache itself spawns nothing and needs no runtime.
  • Storage is pluggable: the cache keeps each resource in a Store created by a Backend. The default DashMapBackend uses sharded concurrent maps with foldhash.
ResourceDefaultLimit::Max countsdiscord.js manager
Guildunlimitedwhole cacheGuildManager
Channelunlimitedwhole cacheChannelManager
Roleunlimitedper guildRoleManager
Userdisabledwhole cacheUserManager
Memberdisabledper guildGuildMemberManager
Messagedisabledper channelMessageManager
Presencedisabledper guildPresenceManager
VoiceStatedisabledper guildVoiceStateManager
Thread, Emoji, Sticker, ScheduledEvent, StageInstance, SoundboardSounddisabledper guildthe guild’s managers

§Examples

Feeding the cache and reading it:

use djs_cache::{Cache, CacheConfig, Limit};
use djs_model::gateway::DispatchEvent;

fn on_event(cache: &Cache, event: &DispatchEvent) {
    if let DispatchEvent::GuildMemberUpdate(update) = event {
        // The member before the update, if it was cached.
        let before = cache.update(&**update);
        let after = cache.members(update.guild_id).get(update.user.id);
        if let (Some(before), Some(after)) = (before, after) {
            if before.nick != after.nick {
                println!("{} is now {}", before.display_name(), after.display_name());
            }
        }
    } else {
        cache.update_dispatch(event);
    }
}

let cache = Cache::with_config(CacheConfig::builder().members(Limit::Unlimited).build());
on_event(&cache, &DispatchEvent::Resumed);

Choosing what to cache:

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

// Guilds, channels and roles only.
let small = Cache::new();
assert!(!small.config().is_enabled(Resource::Member));

// Members too, and the latest 50 messages of every channel.
let config = CacheConfig::builder()
    .members(Limit::Unlimited)
    .messages(Limit::Max(50))
    .build();
let cache = Cache::with_config(config);
assert_eq!(cache.config().limit(Resource::Message), Limit::Max(50));

// discord.js' defaults without presences.
let config = CacheConfigBuilder::from(CacheConfig::discord_js())
    .presences(Limit::Disabled)
    .build();
assert!(config.is_enabled(Resource::VoiceState));

§Part of djs-rs

djs-cache is one crate of djs-rs, a high-performance Rust library for building Discord bots modelled on discord.js v14. It can be used on its own or through the main djs-rs crate.

§License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Structs§

Cache
An in-memory view of Discord state, kept up to date from gateway events.
CacheConfig
Which resources the cache keeps, and how many entries of each.
CacheConfigBuilder
Builds a CacheConfig. Created by CacheConfig::builder, or from an existing configuration with CacheConfigBuilder::from.
CacheView
A resource kept over the whole cache (guilds, channels, users), as returned by Cache::guilds, Cache::channels and Cache::users.
CachedGuild
A cached guild: a [Guild] without its roles, emojis and stickers, which the cache keeps in their own resources, plus what GUILD_CREATE adds.
CachedMember
A cached guild member (D-177): a [Member] with its guild, its user shared with the user resource, and its rarely set fields behind one box.
CachedMessage
A cached message: a [Message] whose author is shared with the user resource, without the member field (members are a resource of their own, D-165).
CachedPresence
A cached presence: a member’s status and activities (D-164).
CachedUser
A cached user (D-177): a [User] with its rarely set fields behind one box.
ChannelView
A resource kept per channel (messages), for one channel, as returned by Cache::messages.
DashMapBackend
The default Backend: every resource is a DashMapStore.
DashMapStore
A Store backed by a sharded concurrent map ([DashMap]), with keys hashed by foldhash.
GuildView
A resource kept per guild (roles, emojis, stickers, members, …), for one guild, as returned by Cache::roles, Cache::members and the like.
Sweep
A periodic sweep: every interval, remove the entries older than lifetime (D-167).
SweepConfig
The periodic sweeps of a CacheConfig (D-167, D-169). Set them with CacheConfigBuilder::sweep_messages and CacheConfigBuilder::sweep_threads.

Enums§

Limit
Whether a Resource is cached, and how many of its entries are kept.
Previous
The previous state returned by Cache::update_dispatch: the UpdateCache::Previous of the event, in a variant per kind.
Resource
A kind of Discord resource the cache can keep.

Traits§

Backend
Creates the Store of each Resource.
Store
The map holding the entries of one Resource.
UpdateCache
A gateway event payload the cache can apply, with the type of the previous state it returns (D-163).