Skip to content

Commit

Permalink
Remove deprecated mapped refs and Cache::channels (#2796)
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev authored Mar 13, 2024
1 parent 6cfbba0 commit f569bd3
Show file tree
Hide file tree
Showing 14 changed files with 97 additions and 329 deletions.
4 changes: 3 additions & 1 deletion src/builder/create_invite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,12 +208,14 @@ impl<'a> CreateInvite<'a> {
self,
cache_http: impl CacheHttp,
channel_id: ChannelId,
guild_id: Option<GuildId>,
) -> Result<RichInvite> {
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
if let (Some(cache), Some(guild_id)) = (cache_http.cache(), guild_id) {
crate::utils::user_has_perms_cache(
cache,
guild_id,
channel_id,
Permissions::CREATE_INSTANT_INVITE,
)?;
Expand Down
4 changes: 2 additions & 2 deletions src/builder/create_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,8 @@ impl<'a> CreateMessage<'a> {
if !self.attachments.is_empty() {
req |= Permissions::ATTACH_FILES;
}
if let Some(cache) = cache_http.cache() {
crate::utils::user_has_perms_cache(cache, channel_id, req)?;
if let (Some(cache), Some(guild_id)) = (cache_http.cache(), guild_id) {
crate::utils::user_has_perms_cache(cache, guild_id, channel_id, req)?;
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/builder/edit_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,18 +307,21 @@ impl<'a> EditChannel<'a> {
self,
cache_http: impl CacheHttp,
channel_id: ChannelId,
guild_id: Option<GuildId>,
) -> Result<GuildChannel> {
#[cfg(feature = "cache")]
{
if let Some(cache) = cache_http.cache() {
if let (Some(cache), Some(guild_id)) = (cache_http.cache(), guild_id) {
crate::utils::user_has_perms_cache(
cache,
guild_id,
channel_id,
Permissions::MANAGE_CHANNELS,
)?;
if self.permission_overwrites.is_some() {
crate::utils::user_has_perms_cache(
cache,
guild_id,
channel_id,
Permissions::MANAGE_ROLES,
)?;
Expand Down
10 changes: 0 additions & 10 deletions src/cache/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ impl CacheUpdate for ChannelCreateEvent {
.get_mut(&self.channel.guild_id)
.and_then(|mut g| g.channels.insert(self.channel.id, self.channel.clone()));

cache.channels.insert(self.channel.id, self.channel.guild_id);
old_channel
}
}
Expand All @@ -59,7 +58,6 @@ impl CacheUpdate for ChannelDeleteEvent {
fn update(&mut self, cache: &Cache) -> Option<VecDeque<Message>> {
let (channel_id, guild_id) = (self.channel.id, self.channel.guild_id);

cache.channels.remove(&channel_id);
cache.guilds.get_mut(&guild_id).map(|mut g| g.channels.remove(&channel_id));

// Remove the cached messages for the channel.
Expand All @@ -71,8 +69,6 @@ impl CacheUpdate for ChannelUpdateEvent {
type Output = GuildChannel;

fn update(&mut self, cache: &Cache) -> Option<GuildChannel> {
cache.channels.insert(self.channel.id, self.channel.guild_id);

cache
.guilds
.get_mut(&self.channel.guild_id)
Expand Down Expand Up @@ -104,9 +100,6 @@ impl CacheUpdate for GuildCreateEvent {
let guild = self.guild.clone();

cache.guilds.insert(self.guild.id, guild);
for channel_id in self.guild.channels.keys() {
cache.channels.insert(*channel_id, self.guild.id);
}

None
}
Expand All @@ -126,9 +119,6 @@ impl CacheUpdate for GuildDeleteEvent {
match cache.guilds.remove(&self.guild.id) {
Some(guild) => {
for channel_id in guild.1.channels.keys() {
// Remove the channel from the cache.
cache.channels.remove(channel_id);

// Remove the channel's cached messages.
cache.messages.remove(channel_id);
}
Expand Down
147 changes: 0 additions & 147 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,19 +105,12 @@ impl<K: Eq + Hash, V, T> std::ops::Deref for CacheRef<'_, K, V, T> {
}
}

type MappedGuildRef<'a, T> = CacheRef<'a, GuildId, T, Guild>;

pub type UserRef<'a> = CacheRef<'a, UserId, User>;
pub type MemberRef<'a> = MappedGuildRef<'a, Member>;
pub type GuildRef<'a> = CacheRef<'a, GuildId, Guild>;
pub type GuildRoleRef<'a> = MappedGuildRef<'a, Role>;
pub type SettingsRef<'a> = CacheRef<'a, (), Settings>;
pub type CurrentUserRef<'a> = CacheRef<'a, (), CurrentUser>;
pub type GuildChannelRef<'a> = MappedGuildRef<'a, GuildChannel>;
pub type GuildRolesRef<'a> = MappedGuildRef<'a, HashMap<RoleId, Role>>;
pub type ChannelMessagesRef<'a> = CacheRef<'a, ChannelId, VecDeque<Message>>;
pub type MessageRef<'a> = CacheRef<'a, ChannelId, Message, VecDeque<Message>>;
pub type GuildChannelsRef<'a> = MappedGuildRef<'a, HashMap<ChannelId, GuildChannel>>;

#[cfg_attr(feature = "typesize", derive(typesize::derive::TypeSize))]
#[derive(Debug)]
Expand Down Expand Up @@ -167,10 +160,6 @@ pub struct Cache {
#[cfg(feature = "temp_cache")]
pub(crate) temp_users: MokaCache<UserId, MaybeOwnedArc<User>, BuildHasher>,

// Channels cache:
/// A map of channel ids to the guilds in which the channel data is stored.
pub(crate) channels: MaybeMap<ChannelId, GuildId>,

// Guilds cache:
// ---
/// A map of guilds with full data available. This includes data like [`Role`]s and [`Emoji`]s
Expand Down Expand Up @@ -243,8 +232,6 @@ impl Cache {
#[cfg(feature = "temp_cache")]
temp_users: temp_cache(settings.time_to_live),

channels: MaybeMap(settings.cache_channels.then(DashMap::default)),

guilds: MaybeMap(settings.cache_guilds.then(DashMap::default)),
unavailable_guilds: MaybeMap(settings.cache_guilds.then(DashMap::default)),

Expand Down Expand Up @@ -338,26 +325,6 @@ impl Cache {
self.guilds.iter().map(|i| *i.key()).chain(unavailable_guild_ids).collect()
}

/// Retrieves a [`GuildChannel`] from the cache based on the given Id.
#[deprecated = "Use Cache::guild and Guild::channels instead"]
pub fn channel(&self, id: ChannelId) -> Option<GuildChannelRef<'_>> {
let guild_id = *self.channels.get(&id)?;
let guild_ref = self.guilds.get(&guild_id)?;
let channel = guild_ref.try_map(|g| g.channels.get(&id)).ok();
if let Some(channel) = channel {
return Some(CacheRef::from_mapped_ref(channel));
}

#[cfg(feature = "temp_cache")]
{
if let Some(channel) = self.temp_channels.get(&id) {
return Some(CacheRef::from_arc(channel));
}
}

None
}

/// Get a reference to the cached messages for a channel based on the given `Id`.
///
/// # Examples
Expand Down Expand Up @@ -402,78 +369,11 @@ impl Cache {
self.guilds.len()
}

/// Retrieves a [`Guild`]'s member from the cache based on the guild's and user's given Ids.
///
/// # Examples
///
/// Retrieving the member object of the user that posted a message, in a
/// [`EventHandler::message`] context:
///
/// ```rust,no_run
/// # use serenity::cache::Cache;
/// # use serenity::http::Http;
/// # use serenity::model::channel::Message;
/// #
/// # async fn run(http: Http, cache: Cache, message: Message) {
/// #
/// let roles_len = {
/// let channel = match cache.channel(message.channel_id) {
/// Some(channel) => channel,
/// None => {
/// if let Err(why) = message.channel_id.say(http, "Error finding channel data").await {
/// println!("Error sending message: {:?}", why);
/// }
/// return;
/// },
/// };
///
/// cache.member(channel.guild_id, message.author.id).map(|m| m.roles.len())
/// };
///
/// let message_res = if let Some(roles_len) = roles_len {
/// let msg = format!("You have {} roles", roles_len);
/// message.channel_id.say(&http, &msg).await
/// } else {
/// message.channel_id.say(&http, "Error finding member data").await
/// };
///
/// if let Err(why) = message_res {
/// println!("Error sending message: {:?}", why);
/// }
/// # }
/// ```
///
/// [`EventHandler::message`]: crate::client::EventHandler::message
/// [`members`]: crate::model::guild::Guild::members
#[deprecated = "Use Cache::guild and Guild::members instead"]
pub fn member(&self, guild_id: GuildId, user_id: UserId) -> Option<MemberRef<'_>> {
let member = self.guilds.get(&guild_id)?.try_map(|g| g.members.get(&user_id)).ok()?;
Some(CacheRef::from_mapped_ref(member))
}

#[deprecated = "Use Cache::guild and Guild::roles instead"]
pub fn guild_roles(&self, guild_id: GuildId) -> Option<GuildRolesRef<'_>> {
let roles = self.guilds.get(&guild_id)?.map(|g| &g.roles);
Some(CacheRef::from_mapped_ref(roles))
}

/// This method clones and returns all unavailable guilds.
pub fn unavailable_guilds(&self) -> ReadOnlyMapRef<'_, GuildId, ()> {
self.unavailable_guilds.as_read_only()
}

/// This method returns all channels from a guild of with the given `guild_id`.
#[deprecated = "Use Cache::guild and Guild::channels instead"]
pub fn guild_channels(&self, guild_id: GuildId) -> Option<GuildChannelsRef<'_>> {
let channels = self.guilds.get(&guild_id)?.map(|g| &g.channels);
Some(CacheRef::from_mapped_ref(channels))
}

/// Returns the number of guild channels in the cache.
pub fn guild_channel_count(&self) -> usize {
self.channels.len()
}

/// Returns the number of shards.
pub fn shard_count(&self) -> NonZeroU16 {
self.shard_data.read().total
Expand Down Expand Up @@ -514,34 +414,6 @@ impl Cache {
Some(CacheRef::from_mapped_ref(message))
}

/// Retrieves a [`Guild`]'s role by their Ids.
///
/// **Note**: This will clone the entire role. Instead, retrieve the guild and retrieve from
/// the guild's [`roles`] map to avoid this.
///
/// # Examples
///
/// Retrieve a role from the cache and print its name:
///
/// ```rust,no_run
/// # use serenity::model::id::{GuildId, RoleId};
/// # use serenity::cache::Cache;
/// #
/// # let cache = Cache::default();
/// // assuming the cache is in scope, e.g. via `Context`
/// if let Some(role) = cache.role(GuildId::new(7), RoleId::new(77)) {
/// println!("Role with Id 77 is called {}", role.name);
/// };
/// ```
///
/// [`Guild`]: crate::model::guild::Guild
/// [`roles`]: crate::model::guild::Guild::roles
#[deprecated = "Use Cache::guild and Guild::roles instead"]
pub fn role(&self, guild_id: GuildId, role_id: RoleId) -> Option<GuildRoleRef<'_>> {
let role = self.guilds.get(&guild_id)?.try_map(|g| g.roles.get(&role_id)).ok()?;
Some(CacheRef::from_mapped_ref(role))
}

/// Returns the settings.
///
/// # Examples
Expand Down Expand Up @@ -572,25 +444,6 @@ impl Cache {
CacheRef::from_guard(self.user.read())
}

/// Returns a channel category matching the given ID
#[deprecated = "Use Cache::guild, Guild::channels, and GuildChannel::kind"]
pub fn category(&self, channel_id: ChannelId) -> Option<GuildChannelRef<'_>> {
#[allow(deprecated)]
let channel = self.channel(channel_id)?;
if channel.kind == ChannelType::Category {
Some(channel)
} else {
None
}
}

/// Returns the parent category of the given channel ID.
#[deprecated = "Use Cache::guild, Guild::channels, and GuildChannel::parent_id"]
pub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId> {
#[allow(deprecated)]
self.channel(channel_id)?.parent_id
}

/// Clones all channel categories in the given guild and returns them.
pub fn guild_categories(&self, guild_id: GuildId) -> Option<HashMap<ChannelId, GuildChannel>> {
let guild = self.guilds.get(&guild_id)?;
Expand Down
14 changes: 3 additions & 11 deletions src/model/channel/channel_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::builder::{
GetMessages,
};
#[cfg(all(feature = "cache", feature = "model"))]
use crate::cache::{Cache, GuildChannelRef};
use crate::cache::Cache;
#[cfg(feature = "collector")]
use crate::collector::{MessageCollector, ReactionCollector};
#[cfg(feature = "collector")]
Expand Down Expand Up @@ -79,7 +79,7 @@ impl ChannelId {
cache_http: impl CacheHttp,
builder: CreateInvite<'_>,
) -> Result<RichInvite> {
builder.execute(cache_http, self).await
builder.execute(cache_http, self, None).await
}

/// Creates a [permission overwrite][`PermissionOverwrite`] for either a single [`Member`] or
Expand Down Expand Up @@ -301,7 +301,7 @@ impl ChannelId {
cache_http: impl CacheHttp,
builder: EditChannel<'_>,
) -> Result<GuildChannel> {
builder.execute(cache_http, self).await
builder.execute(cache_http, self, None).await
}

/// Edits a [`Message`] in the channel given its Id.
Expand Down Expand Up @@ -345,14 +345,6 @@ impl ChannelId {
http.follow_news_channel(self, target_channel_id).await
}

/// Attempts to find a [`GuildChannel`] by its Id in the cache.
#[cfg(feature = "cache")]
#[deprecated = "Use Cache::guild and Guild::channels instead"]
pub fn to_channel_cached(self, cache: &Cache) -> Option<GuildChannelRef<'_>> {
#[allow(deprecated)]
cache.channel(self)
}

/// First attempts to retrieve the channel from the `temp_cache` if enabled, otherwise performs
/// a HTTP request.
///
Expand Down
Loading

0 comments on commit f569bd3

Please sign in to comment.