Optimize Trivia list loading #6336

Merged
Jackenmen merged 2 commits from trivia_optimizations into V3/develop 2024-10-29 18:58:28 +01:00
Jackenmen commented 2024-03-31 03:34:32 +02:00 (Migrated from github.com)

Description of the changes

To support listing descriptions in [p]trivia list, there's a need for further optimizations in the list loading process.

Optimizations made:

  • Updated yaml.safe_load() calls to use of yaml.CSafeLoader (C implementation of the parser) when possible
  • Added a flag for disabling schema validation when it is not strictly needed

The latter change is supposed to help us support retrieval of the actually needed fields without having to validate schema of the whole file, for example:

def _get_list_description(path: pathlib.Path) -> str:
    """
    Returns a trivia list description from the given path.

    Raises
    ------
    InvalidListError
        Parsing of list's YAML file failed.
    """
    trivia_dict = get_list(path, validate_schema=False)
    return str(trivia_dict.get("DESCRIPTION", ""))

@Kreusada here's an example of how we can optimally get trivia descriptions for [p]trivia list output (10 per page in this example + cache for previously generated pages) when you work on it:

import pathlib
from typing import Dict, List

from redbot.vendored.discord.ext import menus as dpy_menus
from redbot.core.utils import views
from redbot.core.utils.chat_formatting import bold, italics


class _TriviasSource(dpy_menus.ListPageSource):
    def __init__(self, items: List[pathlib.Path]):
        super().__init__(items, per_page=10)
        self._cache: Dict[int, str] = {}

    async def get_page(self, page_number: int) -> str:
        cached = self._cache.get(page_number)
        if cached is not None:
            return cached

        categories = await super().get_page(page_number)
        entries = []
        for path in categories:
            description = _get_list_description(path)
            if len(description) > 100:
                description = f"{description[:99]}\N{HORIZONTAL ELLIPSIS}"
            elif not description:
                description = italics(_("No description provided for this category."))

            entries.append(f"- {bold(path.stem)} - {description}")

        ret = "\n".join(entries)
        self._cache[page_number] = ret
        return ret

    async def format_page(
        self, view: discord.ui.View, page: views._ACCEPTABLE_PAGE_TYPES
    ) -> views._ACCEPTABLE_PAGE_TYPES:
        return page


# ...

# in `[p]trivia list` implementation:
items = self._all_lists()
menu = views.SimpleMenu(items)
menu._source = _TriviasSource(items)
await menu.start(ctx)

Have the changes in this PR been tested?

Yes

### Description of the changes To support listing descriptions in `[p]trivia list`, there's a need for further optimizations in the list loading process. Optimizations made: - Updated `yaml.safe_load()` calls to use of `yaml.CSafeLoader` (C implementation of the parser) when possible - Added a flag for disabling schema validation when it is not strictly needed The latter change is supposed to help us support retrieval of the actually needed fields without having to validate schema of the whole file, for example: ```py def _get_list_description(path: pathlib.Path) -> str: """ Returns a trivia list description from the given path. Raises ------ InvalidListError Parsing of list's YAML file failed. """ trivia_dict = get_list(path, validate_schema=False) return str(trivia_dict.get("DESCRIPTION", "")) ``` @Kreusada here's an example of how we can optimally get trivia descriptions for `[p]trivia list` output (10 per page in this example + cache for previously generated pages) when you work on it: ```py import pathlib from typing import Dict, List from redbot.vendored.discord.ext import menus as dpy_menus from redbot.core.utils import views from redbot.core.utils.chat_formatting import bold, italics class _TriviasSource(dpy_menus.ListPageSource): def __init__(self, items: List[pathlib.Path]): super().__init__(items, per_page=10) self._cache: Dict[int, str] = {} async def get_page(self, page_number: int) -> str: cached = self._cache.get(page_number) if cached is not None: return cached categories = await super().get_page(page_number) entries = [] for path in categories: description = _get_list_description(path) if len(description) > 100: description = f"{description[:99]}\N{HORIZONTAL ELLIPSIS}" elif not description: description = italics(_("No description provided for this category.")) entries.append(f"- {bold(path.stem)} - {description}") ret = "\n".join(entries) self._cache[page_number] = ret return ret async def format_page( self, view: discord.ui.View, page: views._ACCEPTABLE_PAGE_TYPES ) -> views._ACCEPTABLE_PAGE_TYPES: return page # ... # in `[p]trivia list` implementation: items = self._all_lists() menu = views.SimpleMenu(items) menu._source = _TriviasSource(items) await menu.start(ctx) ``` ### Have the changes in this PR been tested? Yes
Kreusada (Migrated from github.com) approved these changes 2024-10-29 18:58:20 +01:00
Kreusada (Migrated from github.com) left a comment

LGTM

LGTM
Sign in to join this conversation.
No reviewers
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!6336
No description provided.