[Alias] Create caching to call config less frequently #3788

Merged
TrustyJAID merged 18 commits from alias-caching into V3/develop 2020-04-27 02:25:42 +02:00
TrustyJAID commented 2020-04-24 03:10:06 +02:00 (Migrated from github.com)

Type

  • Bugfix
  • Enhancement
  • New feature

Description of the changes

Add a caching system to Alias to reduce frequency of calls to config. This also re-arranges some functions inside alias to improve readability and usability.

This also changes aliases to be checked on_message_without_command to avoid the potential of loading a cog with a command with the same name as an alias.

### Type - [ ] Bugfix - [x] Enhancement - [ ] New feature ### Description of the changes Add a caching system to Alias to reduce frequency of calls to config. This also re-arranges some functions inside alias to improve readability and usability. This also changes aliases to be checked on_message_without_command to avoid the potential of loading a cog with a command with the same name as an alias.
palmtree5 (Migrated from github.com) reviewed 2020-04-24 03:10:06 +02:00
tekulvw (Migrated from github.com) reviewed 2020-04-24 03:10:06 +02:00
Twentysix26 (Migrated from github.com) reviewed 2020-04-24 03:10:06 +02:00
Jackenmen (Migrated from github.com) requested changes 2020-04-26 20:03:40 +02:00
Jackenmen (Migrated from github.com) commented 2020-04-26 19:30:57 +02:00
This method is used in two other places outside Alias cog: https://github.com/Cog-Creators/Red-DiscordBot/search?q=bot.get_cog%28%22Alias%22%29&unscoped_q=bot.get_cog%28%22Alias%22%29
@ -417,3 +281,4 @@
if await self._aliases.delete_alias(ctx, alias_name, global_=True):
await ctx.send(
_("Alias with the name `{name}` was successfully deleted.").format(name=alias_name)
)
Jackenmen (Migrated from github.com) commented 2020-04-26 03:02:09 +02:00

This doesn't really matter with cache turned on but assuming it would be possible to disable in future, result of this coro should probably be assigned to a variable to avoid calling Config twice.

This doesn't really matter with cache turned on but assuming it would be possible to disable in future, result of this coro should probably be assigned to a variable to avoid calling Config twice.
Jackenmen (Migrated from github.com) commented 2020-04-26 19:48:02 +02:00

This doesn't really matter with cache turned on but assuming it would be possible to disable in future, result of this coro should probably be assigned to a variable to avoid calling Config twice.

This doesn't really matter with cache turned on but assuming it would be possible to disable in future, result of this coro should probably be assigned to a variable to avoid calling Config twice.
@ -32,1 +44,4 @@
def get_extra_args_from_alias(self, message: discord.Message, prefix: str) -> str:
"""
When an alias is executed by a user in chat this function tries
Jackenmen (Migrated from github.com) commented 2020-04-26 02:47:50 +02:00

Considering this returns an AliasEntry object, not a bool, we should call this get_alias instead of is_alias.

Considering this returns an `AliasEntry` object, not a `bool`, we should call this `get_alias` instead of `is_alias`.
Jackenmen (Migrated from github.com) commented 2020-04-26 16:19:42 +02:00

You shouldn't be calling Config on each guild again if you already have all the needed data.

Also, considering all the optimizations for big bots that we've done lately, this should probably be wrapped in AsyncIter class from redbot.core.utils to avoid blocking event loop on alias loading for bigger bots.

        all_guilds = await self.config.all_guilds()
        async for guild_id, guild_data in AsyncIter(all_guilds.items(), steps=100):
            aliases = guild_data["entries"]
You shouldn't be calling Config on each guild again if you already have all the needed data. Also, considering all the optimizations for big bots that we've done lately, this should probably be wrapped in `AsyncIter` class from `redbot.core.utils` to avoid blocking event loop on alias loading for bigger bots. ```suggestion all_guilds = await self.config.all_guilds() async for guild_id, guild_data in AsyncIter(all_guilds.items(), steps=100): aliases = guild_data["entries"] ```
Jackenmen (Migrated from github.com) commented 2020-04-26 16:43:22 +02:00

Could we do this on cog load instead? It would allow us to skip this check in every method accessing the cache and it would assure that this won't be called several times before the cache is fully loaded (i.e. someone spams an alias). If that's not an option for some reason, the parts that load aliases would need some lock.

Could we do this on cog load instead? It would allow us to skip this check in every method accessing the cache and it would assure that this won't be called several times before the cache is fully loaded (i.e. someone spams an alias). If that's not an option for some reason, the parts that load aliases would need some lock.
Jackenmen (Migrated from github.com) commented 2020-04-26 16:46:18 +02:00

(this is mostly a nitpick)
We could use a dict comprehension instead here and (imo) simplify this.

            self._aliases[guild_id] = {
                alias["name"]: AliasEntry.from_json(alias) for alias in aliases
            }
**(this is mostly a nitpick)** We could use a dict comprehension instead here and (imo) simplify this. ```suggestion self._aliases[guild_id] = { alias["name"]: AliasEntry.from_json(alias) for alias in aliases } ```
Jackenmen (Migrated from github.com) commented 2020-04-26 17:22:28 +02:00

It would be faster to search the alias with a key lookup in the cache dict instead of iterating through list of alias objects.

It would be faster to search the alias with a key lookup in the cache dict instead of iterating through list of alias objects.
Jackenmen (Migrated from github.com) commented 2020-04-26 17:24:36 +02:00

Having these as iterators as they were before and chaining them would probably be a little better however you can consider this a nitpick

Having these as iterators as they were before and chaining them would probably be a little better **however you can consider this a nitpick**
Jackenmen (Migrated from github.com) commented 2020-04-26 17:44:03 +02:00

I know this isn't a part of this PR so if you'll leave as is, it's fine.

Could we skip creating alias entry for each alias and just check for alias["name"]?

                if alias["name"] == alias_name:
                    aliases.remove(alias)
                    if self._cache_enabled:
                        if global_:
                            del self._aliases[None][alias["name"]
                        else:
                            del self._aliases[ctx.guild.id][alias["name"]]
**I know this isn't a part of this PR so if you'll leave as is, it's fine.** Could we skip creating alias entry for each alias and just check for `alias["name"]`? ```suggestion if alias["name"] == alias_name: aliases.remove(alias) if self._cache_enabled: if global_: del self._aliases[None][alias["name"] else: del self._aliases[ctx.guild.id][alias["name"]] ```
@ -64,0 +125,4 @@
else:
aliases = [AliasEntry.from_json(d) for d in await self.config.guild(guild).entries()]
return aliases
Jackenmen (Migrated from github.com) commented 2020-04-26 03:10:01 +02:00

There was a reason for this try: except here - we want the JSON dict to have user/guild ID, not Member/Guild object.

With that said, you could probably do an if self.has_real_data instead of try: except

There was a reason for this `try: except` here - we want the JSON dict to have user/guild ID, not Member/Guild object. With that said, you could probably do an `if self.has_real_data` instead of `try: except`
@ -64,0 +168,4 @@
) -> AliasEntry:
indices = findall(r"{(\d*)}", command)
if indices:
try:
Jackenmen (Migrated from github.com) commented 2020-04-26 16:49:00 +02:00

(this is mostly a nitpick)
We could use a dict comprehension instead here and (imo) simplify this.

        aliases = await self.config.entries()
        self._aliases[None] = {alias["name"]: AliasEntry.from_json(alias) for alias in aliases}
**(this is mostly a nitpick)** We could use a dict comprehension instead here and (imo) simplify this. ```suggestion aliases = await self.config.entries() self._aliases[None] = {alias["name"]: AliasEntry.from_json(alias) for alias in aliases} ```
TrustyJAID (Migrated from github.com) reviewed 2020-04-26 20:37:07 +02:00
@ -64,0 +125,4 @@
else:
aliases = [AliasEntry.from_json(d) for d in await self.config.guild(guild).entries()]
return aliases
TrustyJAID (Migrated from github.com) commented 2020-04-26 20:37:07 +02:00

This was removed because I ensured all creation of AliasEntry objects only accepted the ID not the object itself. I'll further ensure that with typehints to only accept int and not the object themselves. They served no purpose being the object and just a reference ID is good enough.

This was removed because I ensured all creation of AliasEntry objects only accepted the ID not the object itself. I'll further ensure that with typehints to only accept int and not the object themselves. They served no purpose being the object and just a reference ID is good enough.
TrustyJAID (Migrated from github.com) reviewed 2020-04-26 20:39:19 +02:00
@ -32,1 +44,4 @@
def get_extra_args_from_alias(self, message: discord.Message, prefix: str) -> str:
"""
When an alias is executed by a user in chat this function tries
TrustyJAID (Migrated from github.com) commented 2020-04-26 20:39:19 +02:00

I was going to but that breaks our tests for the cog.

I was going to but that breaks our tests for the cog.
Jackenmen (Migrated from github.com) reviewed 2020-04-26 20:40:59 +02:00
@ -64,0 +125,4 @@
else:
aliases = [AliasEntry.from_json(d) for d in await self.config.guild(guild).entries()]
return aliases
Jackenmen (Migrated from github.com) commented 2020-04-26 20:40:59 +02:00

I was basing this comment on from_json method which could change it into Member/Guild objects if bot was passed. I know it's never passed so maybe you could just remove this all together or at least add a comment that some changes to AliasEntry would be needed if we would start to pass the bot object

I was basing this comment on `from_json` method which could change it into Member/Guild objects if bot was passed. I know it's never passed so maybe you could just remove this all together or at least add a comment that some changes to `AliasEntry` would be needed if we would start to pass the bot object
Jackenmen (Migrated from github.com) reviewed 2020-04-26 20:43:46 +02:00
@ -32,1 +44,4 @@
def get_extra_args_from_alias(self, message: discord.Message, prefix: str) -> str:
"""
When an alias is executed by a user in chat this function tries
Jackenmen (Migrated from github.com) commented 2020-04-26 20:43:45 +02:00
You can do the loading in the alias fixture here: https://github.com/TrustyJAID/Red-DiscordBot/blob/alias-caching/redbot/pytest/alias.py#L12
TrustyJAID (Migrated from github.com) reviewed 2020-04-26 22:48:57 +02:00
@ -32,1 +44,4 @@
def get_extra_args_from_alias(self, message: discord.Message, prefix: str) -> str:
"""
When an alias is executed by a user in chat this function tries
TrustyJAID (Migrated from github.com) commented 2020-04-26 22:48:57 +02:00

I feel like the current method is more readable and easier for others to verify it's working correctly. List and Dict comprehensions while sometimes make the code look cleaner can also make it less readable and this is one where I think it could be misinterpreted.

I feel like the current method is more readable and easier for others to verify it's working correctly. List and Dict comprehensions while sometimes make the code look cleaner can also make it less readable and this is one where I think it could be misinterpreted.
Jackenmen (Migrated from github.com) requested changes 2020-04-27 01:20:28 +02:00
@ -30,34 +42,182 @@ class AliasEntry:
self.uses += 1
Jackenmen (Migrated from github.com) commented 2020-04-27 01:13:05 +02:00

These need to be opposite order - global aliases take precedence over guild aliases.

            if alias_name in self._aliases[None]:
                return self._aliases[None][alias_name]
            if guild is not None:
                if guild.id in self._aliases:
                    if alias_name in self._aliases[guild.id]:
                        return self._aliases[guild.id][alias_name]

​

If you care for my nitpicks, this code would avoid doing key lookups multiple times, otherwise just ignore this part, I couldn't stop myself from putting this here :P

            if alias := self._aliases[None].get(alias_name):
                return alias
            if guild is not None:
                if guild_aliases := self._aliases.get(guild.id):
                    if alias := guild_aliases.get(guild.id):
                        return alias
These need to be opposite order - global aliases take precedence over guild aliases. ```suggestion if alias_name in self._aliases[None]: return self._aliases[None][alias_name] if guild is not None: if guild.id in self._aliases: if alias_name in self._aliases[guild.id]: return self._aliases[guild.id][alias_name] ``` ​ If you care for my nitpicks, this code would avoid doing key lookups multiple times, otherwise just ignore this part, I couldn't stop myself from putting this here :P ```suggestion if alias := self._aliases[None].get(alias_name): return alias if guild is not None: if guild_aliases := self._aliases.get(guild.id): if alias := guild_aliases.get(guild.id): return alias ```
Jackenmen (Migrated from github.com) reviewed 2020-04-27 02:18:29 +02:00
Jackenmen (Migrated from github.com) approved these changes 2020-04-27 02:24:19 +02:00
Jackenmen (Migrated from github.com) left a comment

Looks good, thanks so much for the PR <3

Looks good, thanks so much for the PR <3
Sign in to join this conversation.
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Mrcoolgamer11/Red-DiscordBot!3788
No description provided.