diff --git a/.dockerignore b/.dockerignore index b5f57d16e..28fb81b84 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,7 +4,9 @@ CONTRIBUTING.md Dockerfile *.env -!.env +tex-bot-deployment.yaml +tex-bot-deployment.*.yaml +tex-bot-deployment.yaml.*.tmp uv.lock pyproject.toml tests diff --git a/.env.example b/.env.example deleted file mode 100644 index 54235e593..000000000 --- a/.env.example +++ /dev/null @@ -1,115 +0,0 @@ -# dotenv-linter:off ValueWithoutQuotes - -# !!REQUIRED!! -# The Discord token for the bot you created (available on your bot page in the developer portal: https://discord.com/developers/applications)) -# Must be a valid Discord bot token (see https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) -DISCORD_BOT_TOKEN=[Replace with your Discord bot token] - -# !!REQUIRED!! -# The ID of the your Discord guild -# Must be a valid Discord guild ID (see https://docs.pycord.dev/en/stable/api/abcs.html#discord.abc.Snowflake.id) -DISCORD_GUILD_ID=[Replace with the ID of the your Discord guild] - -# The webhook URL of the Discord text channel where error logs should be sent -# Error logs will always be sent to the console, this setting allows them to also be sent to a Discord log channel -# Must be a valid Discord channel webhook URL (see https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks) -DISCORD_LOG_CHANNEL_WEBHOOK_URL=[Replace with your Discord log channel webhook URL] - -# The full name of your community group, do NOT use an abbreviation. -# This is substituted into many error/welcome messages sent into your Discord guild, by the bot. -# If this is not set the group-full-name will be retrieved from the name of your group's Discord guild -GROUP_NAME=[Replace with the full name of your community group (not an abbreviation)] - -# The short colloquial name of your community group, it is recommended that you set this to be an abbreviation of your group's name. -# If this is not set the group-short-name will be determined from your group's full name -GROUP_SHORT_NAME=[Replace with the short colloquial name of your community group] - -# The URL of the page where guests can purchase a full membership to join your community group -# Must be a valid URL -PURCHASE_MEMBERSHIP_URL=[Replace with your group\'s purchase-membership URL] - -# The URL of the page containing information about the perks of buying a full membership to join your community group -# Must be a valid URL -MEMBERSHIP_PERKS_URL=[Replace with your group\'s membership-perks URL] - -# The invite link URL to allow users to join your community group's Discord server -# Must be a valid URL -CUSTOM_DISCORD_INVITE_URL=[Replace with your group\'s Discord server invite link] - -# The minimum level that logs must meet in order to be logged to the console output stream -# One of: DEBUG, INFO, WARNING, ERROR, CRITICAL -CONSOLE_LOG_LEVEL=INFO - -# !!REQUIRED!! -# The URL to retrieve the list of IDs of people that have purchased a membership to your community group -# Ensure that all members are visible without pagination. For example, if your members-list is found on the UoB Guild of Students website, ensure the URL includes the "sort by groups" option -# Must be a valid URL -ORGANISATION_ID=[Replace with your group\'s MSL Organisation ID] - -# !!REQUIRED!! -# The cookie required for access to your Student Union's online platform. -# If your group's members-list is stored at a URL that requires authentication, this session cookie should authenticate the bot to view your group's members-list, as if it were logged in to the website as a Committee member -# This can be extracted from your web-browser, after logging in to view your members-list yourself. It will probably be listed as a cookie named `.AspNet.SharedCookie` -SU_PLATFORM_ACCESS_COOKIE=[Replace with your .AspNet.SharedCookie cookie] - -# The probability that the more rare ping command response will be sent instead of the normal one -# Must be a float between & including 0 to 1 -PING_COMMAND_EASTER_EGG_PROBABILITY=0.01 - -# The path to the messages JSON file that contains the common messages sent by the bot -# Must be a path to a JSON file that exists, that contains a JSON string that can be decoded into a Python dict object -MESSAGES_FILE_PATH=messages.json - -# Whether introduction reminders will be sent to Discord members that are not inducted, saying that they need to send an introduction to be allowed access -# One of: Once, Interval, False -SEND_INTRODUCTION_REMINDERS=Once - -# How long to wait after a user joins your guild before sending them the first/only message remind them to send an introduction -# Is ignored if SEND_INTRODUCTION_REMINDERS=False -# Must be a string of the seconds, minutes, hours, days or weeks before the first/only reminder is sent (format: "smhdw") -# The delay must be longer than or equal to 1 day (in any allowed format) -SEND_INTRODUCTION_REMINDERS_DELAY=40h - -# The interval of time between sending out reminders to Discord members that are not inducted, saying that they need to send an introduction to be allowed access -# Is ignored if SEND_INTRODUCTION_REMINDERS=Once or SEND_INTRODUCTION_REMINDERS=False -# Must be a string of the seconds, minutes or hours between reminders (format: "smh") -SEND_INTRODUCTION_REMINDERS_INTERVAL=6h - -# Whether reminders will be sent to Discord members that have been inducted, saying that they can get opt-in roles. (This message will be only sent once per Discord member) -# Must be a boolean (True or False) -SEND_GET_ROLES_REMINDERS=True - -# How long to wait after a user is inducted before sending them the message to get some opt-in roles -# Is ignored if SEND_GET_ROLES_REMINDERS=False -# Must be a string of the seconds, minutes, hours, days or weeks before a reminder is sent (format: "smhdw") -# The delay must be longer than or equal to 1 day (in any allowed format) -SEND_GET_ROLES_REMINDERS_DELAY=40h - -# !!This is an advanced configuration variable, so is unlikely to need to be changed from its default value!! -# The interval of time between sending out reminders to Discord members that have been inducted, saying that they can get opt-in roles. (This message will be only sent once, the interval is just how often the check for new guests occurs) -# Is ignored if SEND_GET_ROLES_REMINDERS=False -# Must be a string of the seconds, minutes or hours between reminders (format: "smh") -ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL=24h - -# The number of days to look over messages sent, to generate statistics data -# Must be a float representing the number of days to look back through -STATISTICS_DAYS=30 - -# The names of the roles to gather statistics about, to display in bar chart graphs -# Must be a comma seperated list of strings of role names -STATISTICS_ROLES=Committee,Committee-Elect,Student Rep,Member,Guest,Server Booster,Foundation Year,First Year,Second Year,Final Year,Year In Industry,Year Abroad,PGT,PGR,Alumnus/Alumna,Postdoc,Quiz Victor - -# !!REQUIRED!! -# The URL of the your group's Discord guild moderation document -# Must be a valid URL -MODERATION_DOCUMENT_URL=[Replace with your group\'s moderation document URL] - -# The name of the channel, that warning messages will be sent to when a committee-member manually applies a moderation action (instead of using the `/strike` command) -# Must be the name of a Discord channel in your group's Discord guild, or the value "DM" (which indicates that the messages will be sent in the committee-member's DMs) -# This can be the name of ANY Discord channel (so the offending person *will* be able to see these messages if a public channel is chosen) -MANUAL_MODERATION_WARNING_MESSAGE_LOCATION=DM - -# The set of roles that are tied to the membership of your community group -# These roles will be removed along with the membership role upon annual handover/reset -# Must be a comma seperated list of strings of role names -MEMBERSHIP_DEPENDENT_ROLES=member-red,member-blue,member-green,member-yellow,member-purple,member-pink,member-orange,member-grey,member-black,member-white diff --git a/.gitattributes b/.gitattributes index a1401149c..b34f90c00 100644 --- a/.gitattributes +++ b/.gitattributes @@ -7,7 +7,6 @@ .toml text eol=lf .md text eol=lf .*ignore text eol=lf -.env* text eol=lf .gitattributes text eol=lf .gitlint text eol=lf .python-version text eol=lf diff --git a/.gitignore b/.gitignore index b0f10b587..591773d77 100644 --- a/.gitignore +++ b/.gitignore @@ -104,6 +104,13 @@ pids .dmypy.json dmypy.json +# TeX-Bot deployment configuration (contains the bot token & other secrets) +tex-bot-deployment.yaml +tex-bot-deployment.*.yaml +!tex-bot-deployment.example.yaml +# NOTE: Written alongside the configuration file whilst it is being rewritten in place. +tex-bot-deployment.yaml.*.tmp + # Environments .env ._env diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1215f7b50..51ee344d6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -44,12 +44,6 @@ repos: - id: zizmor args: [--no-progress, --fix, --persona=auditor] - - repo: https://github.com/dotenv-linter/dotenv-linter - rev: v4.0.0 - hooks: - - id: dotenv-linter - args: [fix, --no-backup] - - repo: https://github.com/hadolint/hadolint rev: v2.15.1 hooks: diff --git a/.yamllint.yaml b/.yamllint.yaml index cd13ce8a8..fbfe2500c 100644 --- a/.yamllint.yaml +++ b/.yamllint.yaml @@ -1,5 +1,13 @@ extends: default +# NOTE: The deployment configuration is written by whoever deploys TeX-Bot, rather than +# being one of this repository's own files. Its settings are ordered to be read from the +# top down (those that must be filled in first, then each section in turn), which the +# alphabetical key ordering required below would destroy. +ignore: | + tex-bot-deployment.*.yaml + tex-bot-deployment.yaml + locale: en_GB.UTF-8 rules: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30a6d14da..c634b6bf4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,16 +52,45 @@ If you are submitting a feature request, please include the steps to implement t ### Top level files * [`main.py`](main.py): is the main entrypoint to instantiate the [`Bot` object](https://docs.pycord.dev/stable/api/clients.html#discord.Bot) & run it -* [`config.py`](config.py): retrieves the [environment variables](README.md#setting-environment-variables) & populates the correct values into the `settings` object +* [`tex-bot-deployment.example.yaml`](tex-bot-deployment.example.yaml): documents every [configuration setting](README.md#configuring-tex-bot) that TeX-Bot understands, along with its default value ### Other significant directories +* [`config/`](config): reads & validates the deployment configuration file, and exposes it as the `settings` object, see [below](#configuration) for more information * [`cogs/`](cogs): contains all the [cogs](https://guide.pycord.dev/popular-topics/cogs) within this project, see [below](#cogs) for more information * [`exceptions/`](exceptions): contains common [exception](https://docs.python.org/3/tutorial/errors) subclasses that may be raised when certain errors occur * [`utils/`](utils): contains common utility classes & functions used by the top-level modules & cogs * [`db/core/models/`](db/core/models): contains all the [database ORM models](https://docs.djangoproject.com/en/stable/topics/db/models) to interact with storing information longer-term (between individual command events) +* [`stubs/`](stubs): contains hand-written [type stubs](https://typing.python.org/en/latest/spec/distributing.html#stub-files) for the third-party packages that do not ship their own * [`tests/`](tests): contains the complete test suite for this project, based on the [Pytest framework](https://pytest.org) +### Configuration + +TeX-Bot is configured by a single [YAML](https://yaml.org) file, which is read, validated & applied by the modules within [the `config` package](config). +Each module owns one concern, so that no other part of the project needs to know how the configuration file is stored: + +* [`config/_schema.py`](config/_schema.py): the single source of truth for the configuration. +Declares every setting as a [Pydantic](https://docs.pydantic.dev) model: its type, its constraints, its default, its help text, whether it holds a secret & whether changing it requires a restart. +**Any new setting is added here, and nowhere else** + +* [`config/_document.py`](config/_document.py): owns every interaction with the file itself; locating it, parsing it while recording the line each setting is written upon, writing it back atomically (without its comments, which cannot be kept beside the right setting once settings are added or removed), & reporting a validation failure against the line that caused it + +* [`config/_accessor.py`](config/_accessor.py): holds the loaded configuration as a single immutable snapshot, replaced wholesale whenever it is reloaded, so that no reader can observe a half-applied configuration + +* [`config/_editor.py`](config/_editor.py): changes an individual setting, on behalf of [the `/config` command](README.md#changing-settings-from-within-discord), validating the result before anything is written + +* [`config/_logging.py`](config/_logging.py): applies the logging settings, replacing existing handlers rather than adding to them, so that reloading cannot accumulate duplicates + +* [`config/_messages.py`](config/_messages.py): loads [the messages file](messages.json), which is held separately from the deployment configuration because it is a body of content rather than a set of settings + +Settings are read as attributes of the `settings` object, by the section holding them: + +```python +import config + +config.settings.commands.ping.easter_egg_probability +``` + ### Cogs [Cogs](https://guide.pycord.dev/popular-topics/cogs) are attachable modules that are loaded onto the [`Bot` instance](https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot). @@ -73,18 +102,34 @@ There are separate cog files for each activity, and one [`__init__.py`](cogs/__i * [`cogs/__init__.py`](cogs/__init__.py): instantiates all the cog classes within this directory +* [`cogs/add_users_to_threads_and_channels.py`](cogs/add_users_to_threads_and_channels.py): cogs for adding Discord members & roles to a channel or thread + +* [`cogs/annual_handover_and_reset.py`](cogs/annual_handover_and_reset.py): cogs for performing your group's annual committee handover & membership reset + * [`cogs/archive.py`](cogs/archive.py): cogs for archiving categories of channels within your group's Discord guild +* [`cogs/check_su_platform_authorisation.py`](cogs/check_su_platform_authorisation.py): cogs for checking whether TeX-Bot is still authenticated to your group's SU platform + * [`cogs/command_error.py`](cogs/command_error.py): cogs for sending error messages when commands fail to complete/execute +* [`cogs/committee_actions_tracking.py`](cogs/committee_actions_tracking.py): cogs for tracking the actions assigned to each committee member + +* [`cogs/config.py`](cogs/config.py): cogs for viewing & changing [TeX-Bot's configuration](README.md#changing-settings-from-within-discord) at run-time + * [`cogs/delete_all.py`](cogs/delete_all.py): cogs for deleting all permanent data stored in a specific object's table in the database * [`cogs/edit_message.py`](cogs/edit_message.py): cogs for editing messages that were previously sent by TeX-Bot +* [`cogs/everest.py`](cogs/everest.py): cogs for calculating how many steps of Mount Everest a university assignment is worth + * [`cogs/induct.py`](cogs/induct.py): cogs for inducting people into your group's Discord guild +* [`cogs/invite_link.py`](cogs/invite_link.py): cogs for sending an invite link to your group's Discord guild + * [`cogs/kill.py`](cogs/kill.py): cogs related to the shutdown of TeX-Bot +* [`cogs/make_applicant.py`](cogs/make_applicant.py): cogs related to making guests into committee applicants + * [`cogs/make_member.py`](cogs/make_member.py): cogs related to making guests into members * [`cogs/ping.py`](cogs/ping.py): cog to request a [ping](https://wikipedia.org/wiki/Ping-pong_scheme#Internet) response diff --git a/Dockerfile b/Dockerfile index dea125fff..906322b99 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,12 +13,20 @@ RUN --mount=type=cache,target=/root/.cache/uv \ uv sync --frozen --no-install-project --no-editable --no-group dev COPY LICENSE /app/ -COPY config.py main.py messages.json /app/ +COPY main.py messages.json /app/ +COPY config/ /app/config/ COPY exceptions/ /app/exceptions/ COPY utils/ /app/utils/ COPY db/ /app/db/ COPY cogs/ /app/cogs/ +# NOTE: The deployment configuration is kept in its own directory, separate from any +# application code, so that it can be mounted as a directory. Mounting the directory +# (rather than the configuration file individually) allows TeX-Bot to rewrite the file +# in place when the `/config` command changes a setting: replacing an individually +# mounted file is rejected, because a rename cannot replace a mount point. +RUN mkdir --parents /app/data + FROM python:3.15-slim-trixie RUN groupadd --system --gid 999 nonroot && useradd --system --gid 999 --uid 999 --create-home nonroot @@ -28,7 +36,8 @@ LABEL org.opencontainers.image.licenses=Apache-2.0 COPY --from=builder --chown=nonroot:nonroot /app /app -ENV LANG=C.UTF-8 PATH="/app/.venv/bin:$PATH" +ENV LANG=C.UTF-8 PATH="/app/.venv/bin:$PATH" \ + TEX_BOT_CONFIG_PATH=/app/data/tex-bot-deployment.yaml WORKDIR /app diff --git a/README.md b/README.md index 60ca570e7..26c686bd4 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Members of your [Discord guild](https://discord.com/developers/docs/resources/gu If a user encounters any of these errors, please communicate the error to the committee member that has been assigned to upkeep & deployment of your instance of TeX-Bot. The meaning of each error code is given here: -* `E1011` - The value for the [environment variable](https://wikipedia.org/wiki/Environment_variable) `DISCORD_GUILD_ID` is an [ID](https://discord.com/developers/docs/reference#snowflakes) that references a [Discord guild](https://discord.com/developers/docs/resources/guild) that does not exist +* `E1011` - The value of the `discord:main-guild-id` [configuration setting](#configuring-tex-bot) is an [ID](https://discord.com/developers/docs/reference#snowflakes) that references a [Discord guild](https://discord.com/developers/docs/resources/guild) that does not exist * `E1021` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Committee**". (This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/write-roles`, `/edit-message`, `/induct`, `/strike`, `/archive`, `/kill`, `/delete-all` & `/ensure-members-inducted` [commands](https://discord.com/developers/docs/interactions/application-commands)) @@ -76,7 +76,7 @@ The meaning of each error code is given here: (This [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) is required for the `/induct` [command](https://discord.com/developers/docs/interactions/application-commands)) * `E1041` - The community group member IDs could not be retrieved from the SU platform. -(It is likely that your `SU_PLATFORM_ACCESS_COOKIE` is invalid. +(It is likely that your `community-group:msl:auth-cookie` [configuration setting](#configuring-tex-bot) is invalid. If your community group is a [Guild of Students](https://guildofstudents.com) [society](https://wikipedia.org/wiki/Student_society), the community group member IDs will be a list of [UoB IDs](https://intranet.birmingham.ac.uk/campus-services/id-cards.aspx)) * `E1042` - The reference to the `@everyone` [role](https://discord.com/developers/docs/topics/permissions#role-object) could not be correctly retrieved. @@ -103,18 +103,23 @@ This may require some changes to the deployment configuration or [an issue about The problem that caused the error should be addressed *immediately*, or otherwise TeX-Bot should be manually shut down to prevent further errors * `CRITICAL` - An **unrecoverable error occurred**. -This level of error will cause TeX-Bot to shut down, as the problem can only be solved by fixing one or more of the [configuration environment variables](https://wikipedia.org/wiki/Environment_variable) +This level of error will cause TeX-Bot to shut down, as the problem can only be solved by fixing one or more of the settings within [your deployment configuration file](#configuring-tex-bot) ## [Repeated Tasks](https://docs.pycord.dev/en/stable/ext/tasks) Conditions -The [configuration variables](https://wikipedia.org/wiki/Environment_variable) `SEND_INTRODUCTION_REMINDERS` & `SEND_GET_ROLES_REMINDERS` determine whether their related [tasks](https://docs.pycord.dev/en/stable/ext/tasks) should run. +The `reminders:send-introduction-reminders:enabled` & `reminders:send-get-roles-reminders:enabled` [configuration settings](#configuring-tex-bot) determine whether their related [tasks](https://docs.pycord.dev/en/stable/ext/tasks) should run. However, because these are rather annoying/drastic actions to be executed automatically, there are additional conditions that must be met on a per-[member](https://discord.com/developers/docs/resources/guild#guild-member-object) basis for the action to trigger. -The conditions for each [task](https://docs.pycord.dev/en/stable/ext/tasks) are listed below, along with the additional [environment variables](https://wikipedia.org/wiki/Environment_variable) that can be used to configure the conditions to suit your needs. +The conditions for each [task](https://docs.pycord.dev/en/stable/ext/tasks) are listed below, along with the additional settings that can be used to configure the conditions to suit your needs. + +> [!IMPORTANT] +> Whether each task is enabled, and the interval it runs at, are fixed when the task is created as TeX-Bot starts up. +> Changing either of them requires TeX-Bot to be restarted; `/config reload` will tell you so. +> The `delay` settings are read each time they are used, so they take effect immediately. | Task Name | Enable/Disable | Per-Member Conditions | Scheduled Interval | |-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `introduction_reminder` | `SEND_INTRODUCTION_REMINDERS`:
* `Once` - Only send the introduction reminder once (even if they later delete the message)
* `Interval` - Send an introduction reminder at a set interval
* `False` - Do not send introduction reminders | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not been inducted (does not have the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) joined your community's guild is greater than `SEND_INTRODUCTION_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not opted out of introduction reminders
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent an introduction reminder. (Only applies when `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`) | The interval of time between this task running is determined by `SEND_INTRODUCTION_REMINDERS_INTERVAL`. (When `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`, all [Discord members](https://discord.com/developers/docs/resources/guild#guild-member-object) will still be checked at this interval, just not sent a message if they have already been sent an introduction reminder). The default interval is to send messages every 6 hours | -| `get_roles_reminder` | `SEND_GET_ROLES_REMINDERS`:
* `True` - A single reminder for the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) will be sent to them only once (even if they later delete the message)
* `False` - Do not send any reminders for [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has been inducted (has the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) does not have any of the opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object). (E.g. "@**First Year**" or "@**Anime**".) (Having the green "@**Member**" [role](https://discord.com/developers/docs/topics/permissions#role-object) or even the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object) makes no difference)
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) was inducted (gained the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object)) is greater than `SEND_GET_ROLES_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent a reminder to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | The interval of time between this task running is determined by `ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL`. It is unlikely that this value will need to be changed from the default of 24 hours | +| `introduction_reminder` | `reminders:send-introduction-reminders:enabled`:
* `once` - Only send the introduction reminder once (even if they later delete the message)
* `interval` - Send an introduction reminder at a set interval
* `false` - Do not send introduction reminders | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not been inducted (does not have the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) joined your community's guild is greater than `reminders:send-introduction-reminders:delay`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not opted out of introduction reminders
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent an introduction reminder. (Only applies when `reminders:send-introduction-reminders:enabled` is set to the value `once`) | The interval of time between this task running is determined by `reminders:send-introduction-reminders:interval`. (When `reminders:send-introduction-reminders:enabled` is set to the value `once`, all [Discord members](https://discord.com/developers/docs/resources/guild#guild-member-object) will still be checked at this interval, just not sent a message if they have already been sent an introduction reminder). The default interval is to send messages every 6 hours | +| `get_roles_reminder` | `reminders:send-get-roles-reminders:enabled`:
* `true` - A single reminder for the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) will be sent to them only once (even if they later delete the message)
* `false` - Do not send any reminders for [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has been inducted (has the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) does not have any of the opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object). (E.g. "@**First Year**" or "@**Anime**".) (Having the green "@**Member**" [role](https://discord.com/developers/docs/topics/permissions#role-object) or even the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object) makes no difference)
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) was inducted (gained the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object)) is greater than `reminders:send-get-roles-reminders:delay`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent a reminder to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | The interval of time between this task running is determined by `reminders:send-get-roles-reminders:interval`. It is unlikely that this value will need to be changed from the default of every 24 hours | ## Deploying in Production @@ -123,9 +128,30 @@ It is can be pulled from the [GitHub Container Registry](https://docs.github.com ([Here is an introduction](https://docs.docker.com/get-started/08_using_compose) on how to use a [docker-compose deployment](https://docs.docker.com/compose).) See [**Versioning**](#versioning) for the full list of available version tags for each release. -Before running the [container](https://docs.docker.com/resources/what-container), some [environment variables](https://wikipedia.org/wiki/Environment_variable) will need to be set. -These can be defined in your [`compose.yaml`](https://docs.docker.com/compose/compose-application-model#the-compose-file) file. -The required [environment variables](https://wikipedia.org/wiki/Environment_variable) are explained within [the "Setting Environment Variables" section](#setting-environment-variables). +Before running the [container](https://docs.docker.com/resources/what-container), you will need to create a deployment configuration file. +This is explained within [the "Configuring TeX-Bot" section](#configuring-tex-bot). + +The container reads its configuration from `/app/data/tex-bot-deployment.yaml`, so mount the **directory** holding your configuration file at `/app/data`: + +```yaml +services: + tex-bot: + image: ghcr.io/cssuob/tex-bot-py-v2:latest + volumes: + - ./tex-bot-data:/app/data +``` + +> [!IMPORTANT] +> Mount the directory, rather than the configuration file itself. +> TeX-Bot rewrites the file in place whenever [the `/config` command](#changing-settings-from-within-discord) changes a setting, and an individually mounted file cannot be replaced. + +The container runs as the non-root user with UID & GID `999`, which must be able to read and write your configuration file: + +```shell +chown -R 999:999 ./tex-bot-data +``` + +To keep your configuration somewhere else within the container, set the `TEX_BOT_CONFIG_PATH` [environment variable](https://wikipedia.org/wiki/Environment_variable) to the full path of the file. ## Local Deployment @@ -151,36 +177,138 @@ It's also handy if you have an empty [Discord guild](https://discord.com/develop The correct [invite URL](https://docs.pycord.dev/en/stable/discord.html#inviting-your-bot) will be displayed to you in the console the first time you run the bot (or if you set a high verbosity log level) -### Setting [Environment Variables](https://wikipedia.org/wiki/Environment_variable) +### Configuring TeX-Bot -You'll also need to set a number of [environment variables](https://wikipedia.org/wiki/Environment_variable) before running TeX-Bot: +TeX-Bot is configured by a single [YAML](https://yaml.org) file, `tex-bot-deployment.yaml`. +Copy [the example file](tex-bot-deployment.example.yaml) to create your own: -* `DISCORD_BOT_TOKEN`: The [Discord bot secret token](https://itexus.com/glossary/discord-bot-token) for the [instance of TeX-Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) you created. - * The [Discord bot token](https://itexus.com/glossary/discord-bot-token) is available on [your bot's page in the Discord Developer Portal](https://discord.com/developers/applications). +```shell +cp tex-bot-deployment.example.yaml tex-bot-deployment.yaml +``` -* `DISCORD_GUILD_ID`: The [ID](https://discord.com/developers/docs/reference#snowflakes) of your community group's [Discord guild](https://discord.com/developers/docs/resources/guild). +By default, this file is read from the repository root. +Set the `TEX_BOT_CONFIG_PATH` [environment variable](https://wikipedia.org/wiki/Environment_variable) to keep it anywhere else. -* `DISCORD_LOG_CHANNEL_WEBHOOK_URL`: The [webhook URL](https://support.discord.com/hc/articles/228383668-Intro-to-Webhooks) of the [Discord text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) where error log messages should be sent. - * This setting is optional. - Error logs will **always** be sent to the [console](https://wikipedia.org/wiki/Terminal_emulator), this setting just allows them to also be sent to a [Discord log channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel). +> [!CAUTION] +> Your configuration file holds your [Discord bot token](https://itexus.com/glossary/discord-bot-token) and your SU platform [session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie). +> Anybody holding either can act as your bot, or read your group's members list. +> It is excluded by [`.gitignore`](.gitignore), so take care not to commit it or share it. -* `ORGANISATION_ID`: Your SU platform organisation ID. This is used to dynamically create the members list and other needed URLs. +Only two settings must be filled in before TeX-Bot will start: -* `SU_PLATFORM_ACCESS_COOKIE`: The SU platform [access session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie). - * This [session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie) will [authenticate](https://wikipedia.org/wiki/Authentication) TeX-Bot to view your group's members list on the SU platform, as if it were [logged in to the website](https://wikipedia.org/wiki/Login_session) as a Committee member. - * This can be [extracted from your web-browser](https://wikihow.com/View-Cookies), after logging in to view your members list yourself. - It will most likely be listed as a [cookie](https://wikipedia.org/wiki/HTTP_cookie) named `.AspNet.SharedCookie`. - * If you wish to test TeX-Bot with the SU platform-access disabled, a dummy value of 128 `0` characters can be used. - Note that this will cause many commands and scheduled tasks to fail when they are used at runtime. +* `discord:bot-token`: The [Discord bot secret token](https://itexus.com/glossary/discord-bot-token) for the [instance of TeX-Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) you created. + * This is available on [your bot's page in the Discord Developer Portal](https://discord.com/developers/applications). -You can put these [variables](https://wikipedia.org/wiki/Environment_variable) in a [`.env` file](https://blog.bitsrc.io/a-gentle-introduction-to-env-files-9ad424cc5ff4) in the root folder, as [python-dotenv](https://saurabh-kumar.com/python-dotenv) is used to collect all [environment variables](https://wikipedia.org/wiki/Environment_variable). -There is an [`.env.example` file](.env.example) in the repo that you can rename and populate. +* `discord:main-guild-id`: The [ID](https://discord.com/developers/docs/reference#snowflakes) of your community group's [Discord guild](https://discord.com/developers/docs/resources/guild). -There are also many other configuration settings that can be changed to alter the behaviour of TeX-Bot. -These are all listed in [the `.env.example` file](.env.example), along with the behaviours that will be affected. +Every other setting is optional, and its default is shown in [the example file](tex-bot-deployment.example.yaml) alongside an explanation of what it affects. +Some of the more commonly changed ones are: -Any [variables](https://wikipedia.org/wiki/Environment_variable), in [the `.env.example` file](.env.example), marked with `# !!REQUIRED!!` must be set before running TeX-Bot. -All other [variables](https://wikipedia.org/wiki/Environment_variable) are optional and their default values are shown as the example value for each variable in [the `.env.example` file](.env.example). +* `logging:discord-channel:webhook-url`: The [webhook URL](https://support.discord.com/hc/articles/228383668-Intro-to-Webhooks) of the [Discord text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) where error log messages should be sent. + * Error logs will **always** be sent to the [console](https://wikipedia.org/wiki/Terminal_emulator); this setting just allows them to also be sent to a [Discord log channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel). + * Omit the whole `logging:discord-channel` section to disable this. + +* `community-group:msl:organisation-id`: Your SU platform organisation ID, used to build your members list & other URLs. + +* `community-group:msl:auth-cookie`: The SU platform [access session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie). + * This [session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie) will [authenticate](https://wikipedia.org/wiki/Authentication) TeX-Bot to view your group's members list on the SU platform, as if it were [logged in to the website](https://wikipedia.org/wiki/Login_session) as a Committee member. + * This can be [extracted from your web-browser](https://wikihow.com/View-Cookies), after logging in to view your members list yourself. + It will most likely be listed as a [cookie](https://wikipedia.org/wiki/HTTP_cookie) named `.AspNet.SharedCookie`. + * Leaving this unset disables SU platform access. + Note that this will cause many commands & scheduled tasks to fail when they are used at runtime. + +> [!NOTE] +> Settings are written in kebab-case & nested into sections. +> Throughout this documentation a setting is named by the path to it, separated by colons: `community-group:msl:auth-cookie` refers to `auth-cookie`, within `msl`, within `community-group`. +> +> Lengths of time are written largest-unit-first, in the format `wdhms`, so `1h30m`, `2d` & `1w` are all valid. +> Capital letters & spaces are ignored, so `1H 30M` is also valid. +> Every part must carry its unit, so a bare `24` is rejected rather than being read as 24 seconds. + +An invalid configuration file is never applied. +TeX-Bot reports the line responsible & keeps running on the last configuration that loaded successfully. + +#### Changing Settings From Within Discord + +Configuration can also be viewed & changed from within [Discord](https://discord.com), without editing the file by hand. +All of these [commands](https://discord.com/developers/docs/interactions/application-commands) require the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object), and reply only to the person that ran them: + +* `/config get `: Shows what a setting is currently set to, & what it affects +* `/config set `: Changes a single setting, then applies it +* `/config unset `: Returns a single setting to its default value. + Unsetting `logging:discord-channel:webhook-url` removes the whole `logging:discord-channel` section, turning off logging to your Discord log channel +* `/config reload`: Reads the configuration file again, applying any changes made to it + +> [!WARNING] +> Changing a setting with `/config set` or `/config unset` rewrites your configuration file **without any comments**. +> Your settings & their order are kept, but every comment & blank line is removed, and the file is rewritten in a standard layout (two-space indents, & one list item per line). +> Keep a copy elsewhere of any notes you want to keep. +> Each setting's description can still be seen with `/config get`. + +Most settings take effect as soon as they are applied, because they are read at the moment they are used. +A few are fixed while TeX-Bot is starting up & cannot be changed without restarting it; `/config reload` will tell you when one of those has changed. + +> [!IMPORTANT] +> If you edit the configuration file by hand, run `/config reload` before using `/config set` or `/config unset`. +> Both refuse to run against a file whose settings have been edited since TeX-Bot last loaded it, so that a change made from within Discord is never quietly mixed together with one made by hand. +> Editing only the comments does not count. + +#### Other [Environment Variables](https://wikipedia.org/wiki/Environment_variable) + +Only two [environment variables](https://wikipedia.org/wiki/Environment_variable) are used, & both are optional: + +* `TEX_BOT_CONFIG_PATH`: The location of your deployment configuration file. + Defaults to `tex-bot-deployment.yaml` within the repository root +* `MESSAGES_FILE_PATH`: The location of [the messages file](messages.json), holding the welcome & roles messages TeX-Bot sends. + Defaults to `messages.json` within the repository root + +#### Migrating From an Older Version + +Earlier versions of TeX-Bot were configured by [environment variables](https://wikipedia.org/wiki/Environment_variable), usually held in a `.env` file. +Those are no longer read at all, & TeX-Bot will not start until a deployment configuration file exists (`tex-bot-deployment.yaml` by default) that sets at least `discord:bot-token` & `discord:main-guild-id`. + +Move each value into your `tex-bot-deployment.yaml`, using the table below. +Where an old variable is not listed, [the example configuration file](tex-bot-deployment.example.yaml) names & explains every setting that exists. + +| Old environment variable | Configuration setting | +|----------------------------------------------|----------------------------------------------------------| +| `DISCORD_BOT_TOKEN` | `discord:bot-token` | +| `DISCORD_GUILD_ID` | `discord:main-guild-id` | +| `DISCORD_LOG_CHANNEL_WEBHOOK_URL` | `logging:discord-channel:webhook-url` | +| `DISCORD_LOG_LEVEL` | `logging:discord-api:log-level` (& set `logging:discord-api:enabled` to `true`) | +| `CONSOLE_LOG_LEVEL` | `logging:console:log-level` | +| `GROUP_NAME` | `community-group:full-name` | +| `GROUP_SHORT_NAME` | `community-group:short-name` | +| `PURCHASE_MEMBERSHIP_URL` | `community-group:links:purchase-membership` | +| `MEMBERSHIP_PERKS_URL` | `community-group:links:membership-perks` | +| `MODERATION_DOCUMENT_URL` | `community-group:links:moderation-policy` | +| `CUSTOM_DISCORD_INVITE_URL` | `community-group:links:custom-discord-invite-link` | +| `MEMBERSHIP_DEPENDENT_ROLES` | `community-group:membership-dependent-roles` | +| `ORGANISATION_ID` | `community-group:msl:organisation-id` | +| `SU_PLATFORM_ACCESS_COOKIE` | `community-group:msl:auth-cookie` | +| `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING` | `community-group:msl:auto-cookie-checking:enabled` | +| `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL` | `community-group:msl:auto-cookie-checking:interval` | +| `PING_COMMAND_EASTER_EGG_PROBABILITY` | `commands:ping:easter-egg-probability` | +| `STATISTICS_DAYS` | `commands:stats:lookback-days` | +| `STATISTICS_ROLES` | `commands:stats:displayed-roles` | +| `MANUAL_MODERATION_WARNING_MESSAGE_LOCATION` | `commands:strike:performed-manually-warning-location` | +| `SEND_INTRODUCTION_REMINDERS` | `reminders:send-introduction-reminders:enabled` | +| `SEND_INTRODUCTION_REMINDERS_DELAY` | `reminders:send-introduction-reminders:delay` | +| `SEND_INTRODUCTION_REMINDERS_INTERVAL` | `reminders:send-introduction-reminders:interval` | +| `SEND_GET_ROLES_REMINDERS` | `reminders:send-get-roles-reminders:enabled` | +| `SEND_GET_ROLES_REMINDERS_DELAY` | `reminders:send-get-roles-reminders:delay` | +| `ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL` | `reminders:send-get-roles-reminders:interval` | +| `AUTO_ADD_COMMITTEE_TO_THREADS` | `auto-add-committee-to-threads` | + +A few differences are worth noting while migrating: + +* Lengths of time are now written largest-unit-first (`1h30m`, not `30m1h`), & a delay is no longer required to be at least one day +* A comma-separated list, such as `STATISTICS_ROLES`, is now written as a [YAML list](https://yaml.org/spec/1.2.2/#collections) +* The level of logs sent to your Discord log channel can now be changed with `logging:discord-channel:log-level`; it used to always be `WARNING`, which is still the default +* `community-group:msl:auto-cookie-checking:interval` now defaults to `10m` (it used to be `24h`), so set it explicitly to keep the old behaviour +* `commands:stats:lookback-days` must now be between `5` & `1826` (`STATISTICS_DAYS` only had to be at least `1`) +* `community-group:msl:organisation-id` & `community-group:msl:auth-cookie` are now optional (`ORGANISATION_ID` & `SU_PLATFORM_ACCESS_COOKIE` used to be required). + Commands & tasks that use your group's MSL website are turned off until both are set, except `/check-su-platform-authorisation`, which only needs the cookie ### Running The Bot diff --git a/cogs/__init__.py b/cogs/__init__.py index 98be47a5a..c8ecfad1e 100644 --- a/cogs/__init__.py +++ b/cogs/__init__.py @@ -62,6 +62,7 @@ CommitteeActionsTrackingContextCommandCog, CommitteeActionsTrackingSlashCommandsCog, ) +from .config import ConfigCommandsCog from .delete_all import DeleteAllCommandsCog from .edit_message import EditMessageCommandCog from .everest import EverestCommandCog @@ -96,6 +97,7 @@ def setup(bot: TeXBot) -> None: CommitteeActionsTrackingSlashCommandsCog, CommitteeActionsTrackingContextCommandCog, CommitteeHandoverCommandCog, + ConfigCommandsCog, DeleteAllCommandsCog, EditMessageCommandCog, EnsureMembersInductedCommandCog, diff --git a/cogs/add_users_to_threads_and_channels.py b/cogs/add_users_to_threads_and_channels.py index 25b0a29f6..5285be36e 100644 --- a/cogs/add_users_to_threads_and_channels.py +++ b/cogs/add_users_to_threads_and_channels.py @@ -168,7 +168,7 @@ async def on_thread_create(self, thread: discord.Thread) -> None: thread.parent is None # noqa: CAR180 or thread.parent.category is None or "committee" not in thread.parent.category.name.lower() - or not settings["AUTO_ADD_COMMITTEE_TO_THREADS"] + or not settings.auto_add_committee_to_threads ): return diff --git a/cogs/annual_handover_and_reset.py b/cogs/annual_handover_and_reset.py index f8d43ecef..e341cb1e5 100644 --- a/cogs/annual_handover_and_reset.py +++ b/cogs/annual_handover_and_reset.py @@ -204,13 +204,13 @@ async def annual_roles_reset(self, ctx: TeXBotApplicationContext) -> None: { role.name: role for role in main_guild.roles - if role.name in settings["MEMBERSHIP_DEPENDENT_ROLES"] + if role.name in settings.community_group.membership_dependent_roles } ) - not_found_role_names: Collection[str] = settings[ - "MEMBERSHIP_DEPENDENT_ROLES" - ] - set(membership_dependent_roles.keys()) + not_found_role_names: Collection[str] = set( + settings.community_group.membership_dependent_roles + ) - set(membership_dependent_roles.keys()) if not_found_role_names: logger.warning( "Membership dependent roles %s were configured but could not be found.", diff --git a/cogs/check_su_platform_authorisation.py b/cogs/check_su_platform_authorisation.py index 158135d77..db86c5681 100644 --- a/cogs/check_su_platform_authorisation.py +++ b/cogs/check_su_platform_authorisation.py @@ -21,7 +21,7 @@ from utils import CommandChecks, TeXBotBaseCog from utils.error_capture_decorators import capture_guild_does_not_exist_error lazy from utils import TeXBot, TeXBotApplicationContext -lazy from utils.msl import fetch_url_content_with_session +lazy from utils.msl import fetch_url_content_with_session, msl_is_configured logger: Final[Logger] = logging.getLogger("TeX-Bot") @@ -70,7 +70,7 @@ async def get_su_platform_access_cookie_status(self) -> SUPlatformAccessCookieSt return SUPlatformAccessCookieStatus.INVALID organisation_admin_url: str = ( - f"{SU_PLATFORM_ORGANISATION_URL}/{settings['ORGANISATION_ID']}" + f"{SU_PLATFORM_ORGANISATION_URL}/{settings.community_group.msl.organisation_id}" ) response_html: str = await fetch_url_content_with_session(organisation_admin_url) @@ -162,6 +162,7 @@ class CheckSUPlatformAuthorisationCommandCog(CheckSUPlatformAuthorisationBaseCog ) @CommandChecks.check_interaction_user_has_committee_role @CommandChecks.check_interaction_user_in_main_guild + @CommandChecks.check_msl_auth_cookie_is_set async def check_su_platform_authorisation(self, ctx: TeXBotApplicationContext) -> None: """ Definition of the "check_su_platform_authorisation" command. @@ -203,7 +204,7 @@ class CheckSUPlatformAuthorisationTaskCog(CheckSUPlatformAuthorisationBaseCog): @override def __init__(self, bot: TeXBot) -> None: """Start all task managers when this cog is initialised.""" - if settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING"]: + if settings.community_group.msl.auto_cookie_checking.enabled: _ = self.su_platform_access_cookie_check_task.start() super().__init__(bot) @@ -217,7 +218,9 @@ def cog_unload(self) -> None: """ self.su_platform_access_cookie_check_task.cancel() - @tasks.loop(**settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL"]) + @tasks.loop( + seconds=settings.community_group.msl.auto_cookie_checking.interval.total_seconds() + ) @capture_guild_does_not_exist_error async def su_platform_access_cookie_check_task(self) -> None: """ @@ -226,6 +229,13 @@ async def su_platform_access_cookie_check_task(self) -> None: The task will check if the cookie is valid and if it is, it will retrieve the MSL organisations the cookie has access to. """ + if not msl_is_configured(): + logger.debug( + "Skipping SU platform access cookie check task, " + "because TeX-Bot has not been fully set up to access your group's MSL website." + ) + return + logger.debug("Running SU platform access cookie check task...") su_platform_access_cookie_status: tuple[int, str] = ( diff --git a/cogs/command_error.py b/cogs/command_error.py index 8ebb0b776..769d8a57e 100644 --- a/cogs/command_error.py +++ b/cogs/command_error.py @@ -57,6 +57,21 @@ async def on_application_command_error( "members can run this command." ) + elif CommandChecks.is_msl_is_configured_failure(error.checks[0]): # type: ignore[arg-type] + message = ( + "This command is unavailable, because TeX-Bot has not been fully set up " + "to access the SU platform. Please contact a committee member, who must " + 'make sure that both the "community-group:msl:organisation-id" & ' + '"community-group:msl:auth-cookie" settings are set, using "/config set".' + ) + + elif CommandChecks.is_msl_auth_cookie_is_set_failure(error.checks[0]): # type: ignore[arg-type] + message = ( + "This command is unavailable, because TeX-Bot has not been fully set up " + "to access the SU platform. Please contact a committee member, who must " + 'set the "community-group:msl:auth-cookie" setting, using "/config set".' + ) + else: logging_message = error diff --git a/cogs/config.py b/cogs/config.py new file mode 100644 index 000000000..6773d6d28 --- /dev/null +++ b/cogs/config.py @@ -0,0 +1,553 @@ +"""Contains cog classes for viewing & changing TeX-Bot's configuration at run-time.""" + +import logging +lazy from collections.abc import Iterable, Mapping, Sequence +lazy from collections.abc import Set as AbstractSet +lazy from logging import Logger +lazy from typing import Final + +import discord + +import config +from config import ( + InvalidSettingsFileError, + SettingsFileChangedError, + SettingsFileNotFoundError, + SettingsNotLoadedError, + SettingsValidationError, + UnknownSettingError, +) +from utils import CommandChecks, TeXBotBaseCog +lazy from config import ConfigReloadResult, ConfigSettingMetadata +lazy from utils import TeXBotApplicationContext, TeXBotAutocompleteContext + +__all__: Sequence[str] = ("ConfigCommandsCog",) + + +logger: Final[Logger] = logging.getLogger("TeX-Bot") + +MAXIMUM_LISTED_SETTINGS: Final[int] = 20 + +# NOTE: The greatest number of suggestions that Discord will display at once. +MAXIMUM_AUTOCOMPLETE_SUGGESTIONS: Final[int] = 25 + +# NOTE: The greatest number of characters Discord will accept within a single message. +MAXIMUM_MESSAGE_LENGTH: Final[int] = 2000 + +TRUNCATION_NOTICE: Final[str] = "\n...(truncated)" + +_EMPTY_ERROR_DETAILS_BLOCK: Final[str] = "```\n\n```" + + +def _truncated(message: str) -> str: + """Shorten the given message to the greatest length that Discord will accept.""" + if len(message) <= MAXIMUM_MESSAGE_LENGTH: + return message + + return ( + message[: MAXIMUM_MESSAGE_LENGTH - len(TRUNCATION_NOTICE)].rstrip() + TRUNCATION_NOTICE + ) + + +def _with_error_details(message: str, configuration_error: object) -> str: + """ + Append the given error to the given message, within a code block. + + The error is shortened where it would take the message beyond the greatest length + Discord will accept, because a message that is too long is refused in its entirety. + A configuration holding many errors would otherwise leave whoever ran the command + with no diagnostic at all, at exactly the moment one is most needed. + """ + AVAILABLE_LENGTH: Final[int] = ( + MAXIMUM_MESSAGE_LENGTH - len(message) - len(_EMPTY_ERROR_DETAILS_BLOCK) + ) + + error_details: str = str(configuration_error) + + if len(error_details) > AVAILABLE_LENGTH: + error_details = ( + error_details[: max(AVAILABLE_LENGTH - len(TRUNCATION_NOTICE), 0)].rstrip() + + TRUNCATION_NOTICE + ) + + return f"{message}```\n{error_details}\n```" + + +def _format_settings_list(settings_names: Iterable[str]) -> str: + """Format the given settings key paths into a bulleted list, truncated if very long.""" + SORTED_SETTINGS_NAMES: Final[Sequence[str]] = sorted(settings_names) + + listed_settings_names: Sequence[str] = SORTED_SETTINGS_NAMES[:MAXIMUM_LISTED_SETTINGS] + + formatted_settings_list: str = "\n".join( + f"- `{settings_name}`" for settings_name in listed_settings_names + ) + + REMAINING_COUNT: Final[int] = len(SORTED_SETTINGS_NAMES) - len(listed_settings_names) + if REMAINING_COUNT > 0: + formatted_settings_list += f"\n- _...and {REMAINING_COUNT} more_" + + return formatted_settings_list + + +def _format_restart_required_warning(restart_required_settings: AbstractSet[str]) -> str: + """Format the warning that a change cannot take effect until TeX-Bot is restarted.""" + if not restart_required_settings: + return "" + + return ( + "\n\n:warning: **TeX-Bot must be restarted " + "before the following take effect:**\n" + f"{_format_settings_list(restart_required_settings)}" + ) + + +def _format_removed_section_notice(removed_section_name: str | None) -> str: + """Format the notice that removing a setting also removed the section requiring it.""" + if removed_section_name is None: + return "" + + return ( + f"\n\n:information_source: The whole of **`{removed_section_name}`** was removed " + "with it, because that section cannot be used without this setting." + ) + + +async def _autocomplete_get_settings_names( + ctx: TeXBotAutocompleteContext, +) -> Sequence[discord.OptionChoice]: + """ + Autocomplete callable that generates the configurable settings names, in order. + + Every setting whose name contains what has been typed so far is suggested, + rather than only those beginning with it, because each name is prefixed with the + section holding it & so is rarely typed from its beginning. + + NOTE: Returned as a sequence, rather than the set that every other autocomplete + callable returns, because these suggestions are alphabetically ordered & a set + would discard that ordering. + + NOTE: Defined at module level, rather than as a staticmethod, because Pycord + fails to recognise a staticmethod referenced by its bare name from within its + own class body as a coroutine function, so never awaits the result. + """ + TYPED_VALUE: Final[str] = str(ctx.value).strip().lower() if ctx.value else "" + + MATCHING_SETTINGS_NAMES: Final[Sequence[str]] = [ + setting_name + for setting_name in config.documented_setting_names() + if TYPED_VALUE in setting_name.lower() + ] + + return [ + discord.OptionChoice(name=setting_name, value=setting_name) + # NOTE: Sliced because Discord refuses a response holding more suggestions + # than it is willing to display. + for setting_name in MATCHING_SETTINGS_NAMES[:MAXIMUM_AUTOCOMPLETE_SUGGESTIONS] + ] + + +class ConfigCommandsCog(TeXBotBaseCog): + """Cog class that defines the "/config" command group & its call-back methods.""" + + config: discord.SlashCommandGroup = discord.SlashCommandGroup( + name="config", + description="View & change TeX-Bot's configuration.", + ) + + @config.command( + name="reload", + description="Reload the configuration file, applying any changes made to it.", + ) + @CommandChecks.check_interaction_user_has_committee_role + @CommandChecks.check_interaction_user_in_main_guild + async def reload(self, ctx: TeXBotApplicationContext) -> None: + """ + Definition & callback response of the "config reload" command. + + Reads the configuration file again, applying every change that can be applied + without restarting TeX-Bot, and reporting any that cannot. + """ + await ctx.defer(ephemeral=True) + + changed_settings: AbstractSet[str] + restart_required_settings: AbstractSet[str] + + configuration_error: Exception + try: + changed_settings, restart_required_settings = config.reload_settings() + except SettingsValidationError as configuration_error: + logger.warning("Configuration reload rejected: %s", configuration_error) + await ctx.respond( + _with_error_details( + ( + ":x: The configuration file was **not** loaded, " + "because it contains invalid settings. " + "No changes have been applied.\n" + ), + configuration_error, + ), + ephemeral=True, + ) + return + except ( + SettingsFileNotFoundError, + InvalidSettingsFileError, + OSError, + ) as configuration_error: + logger.warning("Configuration reload failed: %s", configuration_error) + await ctx.respond( + _with_error_details( + ( + ":x: The configuration file could not be read, " + "so no changes have been applied.\n" + ), + configuration_error, + ), + ephemeral=True, + ) + return + + if not changed_settings: + await ctx.respond( + ":information_source: The configuration file has not changed.", + ephemeral=True, + ) + return + + logger.info("Configuration reloaded: %s setting(s) changed.", len(changed_settings)) + + response_message: str = ( + f":white_check_mark: Reloaded the configuration file. " + f"{len(changed_settings)} setting(s) changed:\n" + f"{_format_settings_list(changed_settings)}" + ) + + response_message += _format_restart_required_warning(restart_required_settings) + + if restart_required_settings and changed_settings - restart_required_settings: + response_message += "\nEvery other change above has already been applied." + + await ctx.respond(response_message, ephemeral=True) + + @config.command( + name="get", + description="Show the current value of a single configuration setting.", + ) + @discord.option( + name="setting", + description="The name of the setting to show.", + input_type=str, + autocomplete=_autocomplete_get_settings_names, + required=True, + parameter_name="setting_name", + ) + @CommandChecks.check_interaction_user_has_committee_role + @CommandChecks.check_interaction_user_in_main_guild + async def get(self, ctx: TeXBotApplicationContext, setting_name: str) -> None: + """ + Definition & callback response of the "config get" command. + + Shows what a single setting is currently set to, along with what it controls. + """ + await ctx.defer(ephemeral=True) + + setting_metadata: ConfigSettingMetadata + try: + setting_metadata = config.setting_metadata(setting_name) + # NOTE: A setting within a section that has been left out of the file + # entirely has no entry of its own, & is simply unset. + CURRENT_VALUE: Final[object] = config.settings.as_flat_mapping().get(setting_name) + except UnknownSettingError as unknown_setting_error: + await self._respond_with_unknown_setting(ctx, unknown_setting_error) + return + except SettingsNotLoadedError: + await ctx.respond( + ":x: No configuration has been loaded, so no setting can be shown.", + ephemeral=True, + ) + return + + IS_SET_WITHIN_FILE: Final[bool] = config.settings.document.contains( + setting_name.split(config.SETTING_NAME_SEPARATOR) + ) + VALUES_AWAITING_RESTART: Final[Mapping[str, object]] = ( + config.settings.values_awaiting_restart + ) + + response_message: str = ( + f"## `{setting_name}`\n" + f"{config.format_setting_value(CURRENT_VALUE, secret=setting_metadata.secret)}" + ) + + # NOTE: A setting holding nothing already says so, & saying that it holds its + # default as well would be saying the same thing twice. A setting awaiting a + # restart is running with its start-up value, which is not necessarily its default. + if ( + not IS_SET_WITHIN_FILE + and CURRENT_VALUE is not None + and setting_name not in VALUES_AWAITING_RESTART + ): + response_message += " _(default; not set within the configuration file)_" + + # NOTE: The value shown above is the one TeX-Bot is running. Showing what the file + # holds alongside it is what stops an edit made since then from looking as though + # it had simply been ignored. The file is compared with the value last loaded from + # it, so that a value only awaiting a restart is not mistaken for such an edit. + if config.settings.file_has_changed(): + response_message += config.format_file_difference( + setting_name, + config.settings.as_flat_file_mapping().get(setting_name), + secret=setting_metadata.secret, + file_path=config.settings.file_path, + ) + + if setting_name in VALUES_AWAITING_RESTART: + response_message += ( + "\n\n:warning: The configuration file changes this to " + f"{ + config.format_setting_value( + VALUES_AWAITING_RESTART[setting_name], secret=setting_metadata.secret + ) + }, which will not take effect until TeX-Bot is restarted." + ) + + if setting_metadata.description: + response_message += f"\n\n{setting_metadata.description}" + + if setting_metadata.requires_restart and setting_name not in VALUES_AWAITING_RESTART: + response_message += ( + "\n\n:warning: Changing this setting requires TeX-Bot to be restarted." + ) + + # NOTE: Shortened because the difference described above holds the error that + # reading an edited file raised, which has no bounded length of its own. + await ctx.respond(_truncated(response_message), ephemeral=True) + + @config.command( + name="set", + description="Change a single configuration setting, then apply the change.", + ) + @discord.option( + name="setting", + description="The name of the setting to change.", + input_type=str, + autocomplete=_autocomplete_get_settings_names, + required=True, + parameter_name="setting_name", + ) + @discord.option( + name="value", + description="The new value, written exactly as it would be within the file.", + input_type=str, + required=True, + min_length=1, + max_length=1000, + parameter_name="raw_value", + ) + @CommandChecks.check_interaction_user_has_committee_role + @CommandChecks.check_interaction_user_in_main_guild + async def set( + self, ctx: TeXBotApplicationContext, setting_name: str, raw_value: str + ) -> None: + """ + Definition & callback response of the "config set" command. + + Writes a single setting into the configuration file & applies it. The new value + is validated first, so a value that would be rejected changes nothing at all. + """ + await ctx.defer(ephemeral=True) + + reload_result: ConfigReloadResult + try: + setting_metadata: ConfigSettingMetadata = config.setting_metadata(setting_name) + reload_result = config.set_setting(setting_name, raw_value) + except UnknownSettingError as unknown_setting_error: + await self._respond_with_unknown_setting(ctx, unknown_setting_error) + return + except SettingsFileChangedError: + await self._respond_with_changed_file(ctx) + return + except SettingsValidationError as validation_error: + await self._respond_with_rejected_change(ctx, setting_name, validation_error) + return + except ( + SettingsFileNotFoundError, + InvalidSettingsFileError, + OSError, + ) as configuration_error: + await self._respond_with_unusable_file(ctx, configuration_error) + return + + # NOTE: The value itself is deliberately not repeated back, so that setting a + # secret cannot leave a copy of it within a Discord channel. + FORMATTED_NEW_VALUE: Final[str] = config.format_setting_value( + config.settings.as_flat_file_mapping()[setting_name], + secret=setting_metadata.secret, + ) + + logger.info("Configuration setting %r changed via the /config command.", setting_name) + + await ctx.respond( + ( + f":white_check_mark: Set **`{setting_name}`** to " + f"{FORMATTED_NEW_VALUE}." + f"{_format_restart_required_warning(reload_result.restart_required_settings)}" + ), + ephemeral=True, + ) + + @config.command( + name="unset", + description="Return a single configuration setting to its default value.", + ) + @discord.option( + name="setting", + description="The name of the setting to return to its default value.", + input_type=str, + autocomplete=_autocomplete_get_settings_names, + required=True, + parameter_name="setting_name", + ) + @CommandChecks.check_interaction_user_has_committee_role + @CommandChecks.check_interaction_user_in_main_guild + async def unset(self, ctx: TeXBotApplicationContext, setting_name: str) -> None: + """ + Definition & callback response of the "config unset" command. + + Removes a single setting from the configuration file, returning it to its + default value. A setting that is required cannot be removed, because the + configuration that removing it would produce is not one TeX-Bot could load. + Removing a setting that an optional section cannot be used without removes the + whole of that section with it. + """ + await ctx.defer(ephemeral=True) + + reload_result: ConfigReloadResult | None + try: + setting_metadata: ConfigSettingMetadata = config.setting_metadata(setting_name) + reload_result = config.unset_setting(setting_name) + except UnknownSettingError as unknown_setting_error: + await self._respond_with_unknown_setting(ctx, unknown_setting_error) + return + except SettingsFileChangedError: + await self._respond_with_changed_file(ctx) + return + except SettingsValidationError as validation_error: + await ctx.respond( + _with_error_details( + ( + f":x: **`{setting_name}`** was **not** removed, because the " + f"configuration would no longer be valid without it. " + f"Nothing has been changed.\n" + ), + validation_error, + ), + ephemeral=True, + ) + return + except ( + SettingsFileNotFoundError, + InvalidSettingsFileError, + OSError, + ) as configuration_error: + await self._respond_with_unusable_file(ctx, configuration_error) + return + + if reload_result is None: + await ctx.respond( + ( + f":information_source: **`{setting_name}`** is not set within the " + f"configuration file, so it is already using its default value." + ), + ephemeral=True, + ) + return + + logger.info("Configuration setting %r removed via the /config command.", setting_name) + + await ctx.respond( + ( + f":white_check_mark: Removed **`{setting_name}`**, " + f"which has returned to its default value of " + f"{ + config.format_setting_value( + config.settings.as_flat_file_mapping()[setting_name], + secret=setting_metadata.secret, + ) + }." + f"{ + _format_removed_section_notice( + setting_metadata.required_by_optional_section + ) + }" + f"{_format_restart_required_warning(reload_result.restart_required_settings)}" + ), + ephemeral=True, + ) + + @classmethod + async def _respond_with_unknown_setting( + cls, ctx: TeXBotApplicationContext, unknown_setting_error: UnknownSettingError + ) -> None: + """Explain that the named setting is not one that TeX-Bot has.""" + await ctx.respond( + ( + f":x: {unknown_setting_error}\n" + "Choose a setting from the suggestions shown as you type." + ), + ephemeral=True, + ) + + @classmethod + async def _respond_with_changed_file(cls, ctx: TeXBotApplicationContext) -> None: + """Explain that the configuration file has been edited since it was loaded.""" + logger.info("A change was refused because the configuration file had been edited.") + + await ctx.respond( + ( + ":x: The configuration file has been edited since TeX-Bot last loaded " + "it, so nothing has been changed.\n" + "Run `/config reload` to load those edits first, then try again." + ), + ephemeral=True, + ) + + @classmethod + async def _respond_with_rejected_change( + cls, + ctx: TeXBotApplicationContext, + setting_name: str, + validation_error: SettingsValidationError, + ) -> None: + """Explain that the given value was refused, & that nothing has been changed.""" + logger.warning("Change to %r rejected: %s", setting_name, validation_error) + + await ctx.respond( + _with_error_details( + ( + f":x: **`{setting_name}`** was **not** changed, because that value is " + f"not valid. Nothing has been changed.\n" + ), + validation_error, + ), + ephemeral=True, + ) + + @classmethod + async def _respond_with_unusable_file( + cls, ctx: TeXBotApplicationContext, configuration_error: Exception + ) -> None: + """Explain that the configuration file itself could not be read or written.""" + logger.warning("Configuration file could not be used: %s", configuration_error) + + await ctx.respond( + _with_error_details( + ( + ":x: The configuration file could not be read or written, " + "so nothing has been changed.\n" + ), + configuration_error, + ), + ephemeral=True, + ) diff --git a/cogs/induct.py b/cogs/induct.py index a7e8df16e..6b446a91c 100644 --- a/cogs/induct.py +++ b/cogs/induct.py @@ -20,7 +20,7 @@ from utils import CommandChecks, TeXBotBaseCog from utils.error_capture_decorators import capture_guild_does_not_exist_error -lazy from config import settings +lazy from config import messages, settings lazy from db.core.models import IntroductionReminderOptOutMember lazy from exceptions import ( ApplicantRoleDoesNotExistError, @@ -105,14 +105,27 @@ async def on_member_update(self, before: discord.Member, after: discord.Member) ] if user_type != "member": + # NOTE: Both links are optional, so the sentence pointing at each one is left + # out entirely rather than sent holding a link that goes nowhere. + PURCHASE_MEMBERSHIP_MESSAGE: Final[str] = ( + f"Just head to {settings.community_group.links.purchase_membership}. " + if settings.community_group.links.purchase_membership is not None + else "" + ) + MEMBERSHIP_PERKS_MESSAGE: Final[str] = ( + f" Checkout all the perks at {settings.community_group.links.membership_perks}" + if settings.community_group.links.membership_perks is not None + else "" + ) + messages_to_send.append( f"You can also get yourself an annual membership " f"to {self.bot.group_full_name} for only £5! " - f"Just head to {settings['PURCHASE_MEMBERSHIP_URL']}. " + f"{PURCHASE_MEMBERSHIP_MESSAGE}" "You'll get awesome perks like a free T-shirt:shirt:, " "access to member only events:calendar_spiral: and a cool green name on " - f"the {self.bot.group_short_name} Discord server:green_square:! " - f"Checkout all the perks at {settings['MEMBERSHIP_PERKS_URL']}" + f"the {self.bot.group_short_name} Discord server:green_square:!" + f"{MEMBERSHIP_PERKS_MESSAGE}" ) try: @@ -137,7 +150,7 @@ async def get_random_welcome_message( self, induction_member: discord.User | discord.Member | None = None ) -> str: """Get & format a random welcome message.""" - random_welcome_message: str = random.choice(tuple(settings["WELCOME_MESSAGES"])) # noqa: S311 + random_welcome_message: str = random.choice(tuple(messages.welcome_messages)) # noqa: S311 if "" in random_welcome_message: if not induction_member: @@ -158,11 +171,12 @@ async def get_random_welcome_message( ) if "" in random_welcome_message: - if not settings["PURCHASE_MEMBERSHIP_URL"]: + if not settings.community_group.links.purchase_membership: return await self.get_random_welcome_message(induction_member) random_welcome_message = random_welcome_message.replace( - "", settings["PURCHASE_MEMBERSHIP_URL"] + "", + str(settings.community_group.links.purchase_membership), ) if "" in random_welcome_message: diff --git a/cogs/invite_link.py b/cogs/invite_link.py index e2b3267bd..91c2067c7 100644 --- a/cogs/invite_link.py +++ b/cogs/invite_link.py @@ -19,7 +19,11 @@ class InviteLinkCommandCog(TeXBotBaseCog): ) async def invite_link(self, ctx: TeXBotApplicationContext) -> None: """Definition & callback response of the "invite_link" command.""" - discord_invite_url: str | None = settings["CUSTOM_DISCORD_INVITE_URL"] + discord_invite_url: str | None = ( + str(settings.community_group.links.custom_discord_invite_link) + if settings.community_group.links.custom_discord_invite_link + else None + ) if not discord_invite_url: invite_destination_channel: discord.TextChannel | None = discord.utils.get( diff --git a/cogs/make_member.py b/cogs/make_member.py index 7bb6d7e6c..2378502ce 100644 --- a/cogs/make_member.py +++ b/cogs/make_member.py @@ -24,16 +24,16 @@ _GROUP_MEMBER_ID_ARGUMENT_DESCRIPTIVE_NAME: Final[str] = f"""{ "Student" if ( - settings["_GROUP_FULL_NAME"] + settings.community_group.full_name and ( - "computer science society" in settings["_GROUP_FULL_NAME"].lower() # noqa: CAR180 - or "css" in settings["_GROUP_FULL_NAME"].lower() - or "uob" in settings["_GROUP_FULL_NAME"].lower() - or "university of birmingham" in settings["_GROUP_FULL_NAME"].lower() - or "uob" in settings["_GROUP_FULL_NAME"].lower() + "computer science society" in settings.community_group.full_name.lower() # noqa: CAR180 + or "css" in settings.community_group.full_name.lower() + or "uob" in settings.community_group.full_name.lower() + or "university of birmingham" in settings.community_group.full_name.lower() + or "uob" in settings.community_group.full_name.lower() or ( - "bham" in settings["_GROUP_FULL_NAME"].lower() - and "uni" in settings["_GROUP_FULL_NAME"].lower() + "bham" in settings.community_group.full_name.lower() + and "uni" in settings.community_group.full_name.lower() ) ) ) @@ -61,16 +61,18 @@ class MakeMemberCommandCog(TeXBotBaseCog): f"""Your UoB Student { "UoB Student" if ( - settings["_GROUP_FULL_NAME"] + settings.community_group.full_name and ( - "computer science society" in settings["_GROUP_FULL_NAME"].lower() # noqa: CAR180 - or "css" in settings["_GROUP_FULL_NAME"].lower() - or "uob" in settings["_GROUP_FULL_NAME"].lower() - or "university of birmingham" in settings["_GROUP_FULL_NAME"].lower() - or "uob" in settings["_GROUP_FULL_NAME"].lower() + "computer science society" # noqa: CAR180 + in settings.community_group.full_name.lower() + or "css" in settings.community_group.full_name.lower() + or "uob" in settings.community_group.full_name.lower() + or "university of birmingham" + in settings.community_group.full_name.lower() + or "uob" in settings.community_group.full_name.lower() or ( - "bham" in settings["_GROUP_FULL_NAME"].lower() - and "uni" in settings["_GROUP_FULL_NAME"].lower() + "bham" in settings.community_group.full_name.lower() + and "uni" in settings.community_group.full_name.lower() ) ) ) @@ -84,6 +86,7 @@ class MakeMemberCommandCog(TeXBotBaseCog): parameter_name="raw_group_member_id", ) @CommandChecks.check_interaction_user_in_main_guild + @CommandChecks.check_msl_is_configured async def make_member( self, ctx: TeXBotApplicationContext, raw_group_member_id: str ) -> None: @@ -208,6 +211,7 @@ class MemberCountCommandCog(TeXBotBaseCog): @discord.slash_command( name="member-count", description="Displays the number of members in the group." ) + @CommandChecks.check_msl_is_configured async def member_count(self, ctx: TeXBotApplicationContext) -> None: """Definition & callback response of the "member_count" command.""" await ctx.defer(ephemeral=False) diff --git a/cogs/ping.py b/cogs/ping.py index 8bacb86bb..3055508d6 100644 --- a/cogs/ping.py +++ b/cogs/ping.py @@ -21,9 +21,11 @@ async def ping(self, ctx: TeXBotApplicationContext) -> None: await ctx.respond( random.choices( # noqa: S311 ["Pong!", "`64 bytes from TeX-Bot: icmp_seq=1 ttl=63 time=0.01 ms`"], + # NOTE: The probability is held as a fraction between 0 & 1, so the + # weight of the common response is the remainder of that same scale. weights=( - 100 - settings["PING_COMMAND_EASTER_EGG_PROBABILITY"], - settings["PING_COMMAND_EASTER_EGG_PROBABILITY"], + 1 - settings.commands.ping.easter_egg_probability, + settings.commands.ping.easter_egg_probability, ), )[0], ephemeral=True, diff --git a/cogs/send_get_roles_reminders.py b/cogs/send_get_roles_reminders.py index 8a5967c8a..0a21cf091 100644 --- a/cogs/send_get_roles_reminders.py +++ b/cogs/send_get_roles_reminders.py @@ -34,7 +34,7 @@ class SendGetRolesRemindersTaskCog(TeXBotBaseCog): @override def __init__(self, bot: TeXBot) -> None: """Start all task managers when this cog is initialised.""" - if settings["SEND_GET_ROLES_REMINDERS"]: + if settings.reminders.send_get_roles_reminders.enabled: _ = self.send_get_roles_reminders.start() super().__init__(bot) @@ -48,7 +48,7 @@ def cog_unload(self) -> None: """ self.send_get_roles_reminders.cancel() - @tasks.loop(**settings["ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL"]) + @tasks.loop(seconds=settings.reminders.send_get_roles_reminders.interval.total_seconds()) @functools.partial( ErrorCaptureDecorators.capture_error_and_close, error_type=GuestRoleDoesNotExistError, @@ -143,7 +143,10 @@ async def send_get_roles_reminders(self) -> None: time_since_role_received: datetime.timedelta = ( discord.utils.utcnow() - guest_role_received_time ) - if time_since_role_received <= settings["SEND_GET_ROLES_REMINDERS_DELAY"]: + if ( + time_since_role_received + <= settings.reminders.send_get_roles_reminders.delay + ): continue if ( diff --git a/cogs/send_introduction_reminders.py b/cogs/send_introduction_reminders.py index 2a4d8327c..31e5111b2 100644 --- a/cogs/send_introduction_reminders.py +++ b/cogs/send_introduction_reminders.py @@ -40,8 +40,8 @@ class SendIntroductionRemindersTaskCog(TeXBotBaseCog): @override def __init__(self, bot: TeXBot) -> None: """Start all task managers when this cog is initialised.""" - if settings["SEND_INTRODUCTION_REMINDERS"]: - if settings["SEND_INTRODUCTION_REMINDERS"] == "interval": + if settings.reminders.send_introduction_reminders.enabled: + if settings.reminders.send_introduction_reminders.enabled == "interval": SentOneOffIntroductionReminderMember.objects.all().delete() _ = self.send_introduction_reminders.start() @@ -62,7 +62,9 @@ async def on_ready(self) -> None: """Add OptOutIntroductionRemindersView to the bot's list of permanent views.""" self.bot.add_view(self.OptOutIntroductionRemindersView(self.bot)) - @tasks.loop(**settings["SEND_INTRODUCTION_REMINDERS_INTERVAL"]) + @tasks.loop( + seconds=settings.reminders.send_introduction_reminders.interval.total_seconds() + ) @functools.partial( ErrorCaptureDecorators.capture_error_and_close, error_type=GuestRoleDoesNotExistError, @@ -100,7 +102,7 @@ async def send_introduction_reminders(self) -> None: continue member_needs_one_off_reminder: bool = ( - settings["SEND_INTRODUCTION_REMINDERS"] == "once" + settings.reminders.send_introduction_reminders.enabled == "once" and not await ( SentOneOffIntroductionReminderMember.objects.filter( discord_member__discord_id=member.id, @@ -108,11 +110,11 @@ async def send_introduction_reminders(self) -> None: ).aexists() ) member_needs_recurring_reminder: bool = ( - settings["SEND_INTRODUCTION_REMINDERS"] == "interval" + settings.reminders.send_introduction_reminders.enabled == "interval" ) member_recently_joined: bool = ( discord.utils.utcnow() - member.joined_at - ) <= settings["SEND_INTRODUCTION_REMINDERS_DELAY"] + ) <= settings.reminders.send_introduction_reminders.delay member_opted_out_from_reminders: bool = await ( IntroductionReminderOptOutMember.objects.filter( discord_member__discord_id=member.id, @@ -164,7 +166,7 @@ async def send_introduction_reminders(self) -> None: ), view=( self.OptOutIntroductionRemindersView(self.bot) - if settings["SEND_INTRODUCTION_REMINDERS"] == "interval" + if settings.reminders.send_introduction_reminders.enabled == "interval" else None # type: ignore[arg-type] ), ) diff --git a/cogs/startup.py b/cogs/startup.py index 5a164a3fa..0f6010709 100644 --- a/cogs/startup.py +++ b/cogs/startup.py @@ -8,11 +8,10 @@ lazy from typing import Final lazy import discord -lazy from discord_logging.handler import DiscordHandler from utils import TeXBotBaseCog lazy import utils -lazy from config import settings +lazy from config import set_discord_log_channel_identity, settings lazy from exceptions import ( ArchivistRoleDoesNotExistError, CommitteeRoleDoesNotExistError, @@ -23,7 +22,7 @@ MSLMembershipError, RolesChannelDoesNotExistError, ) -lazy from utils.msl import fetch_community_group_members_list +lazy from utils.msl import fetch_community_group_members_list, msl_is_configured logger: Final[Logger] = logging.getLogger("TeX-Bot") @@ -38,33 +37,20 @@ async def on_ready(self) -> None: Shortcut accessors should only be populated once TeX-Bot is ready to make API requests. """ - if settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"]: - discord_logging_handler: logging.Handler = DiscordHandler( - service_name=self.bot.user.name if self.bot.user else "TeX-Bot", - webhook_url=settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"], - avatar_url=( - self.bot.user.avatar.url - if self.bot.user and self.bot.user.avatar - else None - ), - ) - discord_logging_handler.setLevel(logging.WARNING) - discord_logging_handler.setFormatter( - logging.Formatter("{levelname} | {message}", style="{") - ) - - logger.addHandler(discord_logging_handler) - - else: - logger.warning( - "DISCORD_LOG_CHANNEL_WEBHOOK_URL was not set, " - "so error logs will not be sent to the Discord log channel." + # NOTE: Relaying error logs to a Discord log channel is set up from the loaded + # configuration (& re-applied upon every reload), rather than here. Attaching a + # handler here as well would relay every error twice, & once more for every + # gateway re-identify, because this listener runs again upon each reconnection. + # Only TeX-Bot's own name & avatar are filled in here, once they are known. + if self.bot.user: + set_discord_log_channel_identity( + self.bot.user.name, self.bot.user.display_avatar.url ) try: main_guild: discord.Guild | None = self.bot.main_guild except GuildDoesNotExistError: - main_guild = self.bot.get_guild(settings["_DISCORD_MAIN_GUILD_ID"]) + main_guild = self.bot.get_guild(settings.discord.main_guild_id) if main_guild: self.bot.set_main_guild(main_guild) @@ -73,19 +59,17 @@ async def on_ready(self) -> None: logger.info( "Invite URL: %s", utils.generate_invite_url( - self.bot.application_id, settings["_DISCORD_MAIN_GUILD_ID"] + self.bot.application_id, settings.discord.main_guild_id ), ) - logger.critical( - GuildDoesNotExistError(guild_id=settings["_DISCORD_MAIN_GUILD_ID"]) - ) + logger.critical(GuildDoesNotExistError(guild_id=settings.discord.main_guild_id)) await self.bot.close() if self.bot.application_id: logger.debug( "Invite URL: %s", utils.generate_invite_url( - self.bot.application_id, settings["_DISCORD_MAIN_GUILD_ID"] + self.bot.application_id, settings.discord.main_guild_id ), ) @@ -107,19 +91,27 @@ async def on_ready(self) -> None: if not discord.utils.get(main_guild.text_channels, name="general"): logger.warning(GeneralChannelDoesNotExistError()) - try: - await fetch_community_group_members_list() - except MSLMembershipError as msl_membership_error: - logger.debug( - "Failed to update community group member list cache on startup: %s", - msl_membership_error, + if not msl_is_configured(): + logger.warning( + "Both 'community-group:msl:organisation-id' & " + "'community-group:msl:auth-cookie' must be set for your group's " + "members-list to be retrieved. Every feature that depends upon knowing " + "who holds a membership will not work until they are." ) + else: + try: + await fetch_community_group_members_list() + except MSLMembershipError as msl_membership_error: + logger.debug( + "Failed to update community group member list cache on startup: %s", + msl_membership_error, + ) - if settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"] != "DM": + if settings.commands.strike.performed_manually_warning_location != "DM": manual_moderation_warning_message_location_exists: bool = bool( discord.utils.get( main_guild.text_channels, - name=settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"], + name=settings.commands.strike.performed_manually_warning_location, ) ) if not manual_moderation_warning_message_location_exists: @@ -128,11 +120,12 @@ async def on_ready(self) -> None: "The channel %s does not exist, so cannot be used as the location " "for sending manual-moderation warning messages" ), - repr(settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"]), + repr(settings.commands.strike.performed_manually_warning_location), + ) + manual_moderation_warning_message_location_similar_to_dm: bool = ( + settings.commands.strike.performed_manually_warning_location.lower() + in ("dm", "dms") ) - manual_moderation_warning_message_location_similar_to_dm: bool = settings[ - "STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION" - ].lower() in ("dm", "dms") if manual_moderation_warning_message_location_similar_to_dm: logger.info( ( diff --git a/cogs/stats/__init__.py b/cogs/stats/__init__.py index d104f0537..f805670a6 100644 --- a/cogs/stats/__init__.py +++ b/cogs/stats/__init__.py @@ -25,8 +25,8 @@ class StatsCommandsCog(TeXBotBaseCog): _DISCORD_SERVER_NAME: Final[str] = f"""{ "the " if ( - settings["_GROUP_SHORT_NAME"] is not None - and (settings["_GROUP_SHORT_NAME"]) + settings.community_group.short_name is not None + and (settings.community_group.short_name) .replace("the", "") .replace("THE", "") .replace("The", "") @@ -35,15 +35,15 @@ class StatsCommandsCog(TeXBotBaseCog): else "" }{ ( - (settings["_GROUP_SHORT_NAME"]) + (settings.community_group.short_name) .replace("the", "") .replace("THE", "") .replace("The", "") .strip() ) if ( - settings["_GROUP_SHORT_NAME"] is not None - and (settings["_GROUP_SHORT_NAME"]) + settings.community_group.short_name is not None + and (settings.community_group.short_name) .replace("the", "") .replace("THE", "") .replace("The", "") @@ -127,7 +127,9 @@ async def channel_stats(self, ctx: TeXBotApplicationContext, str_channel_id: str x_label="Role Name", y_label=( f"""Number of Messages Sent (in the past { - amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day") + amount_of_time_formatter( + settings.commands.stats.lookback_period.days, "day" + ) })""" ), title=f"Most Active Roles in #{channel.name}", @@ -193,7 +195,9 @@ async def server_stats(self, ctx: TeXBotApplicationContext) -> None: x_label="Role Name", y_label=( f"""Number of Messages Sent (in the past { - amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day") + amount_of_time_formatter( + settings.commands.stats.lookback_period.days, "day" + ) })""" ), title=( @@ -215,7 +219,9 @@ async def server_stats(self, ctx: TeXBotApplicationContext) -> None: x_label="Channel Name", y_label=( f"""Number of Messages Sent (in the past { - amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day") + amount_of_time_formatter( + settings.commands.stats.lookback_period.days, "day" + ) })""" ), title=( @@ -281,7 +287,7 @@ async def user_stats(self, ctx: TeXBotApplicationContext) -> None: message_counts[f"#{channel.name}"] = 0 message_history_period: AsyncIterable[discord.Message] = channel.history( - after=discord.utils.utcnow() - settings["STATISTICS_DAYS"] + after=discord.utils.utcnow() - settings.commands.stats.lookback_period ) message: discord.Message async for message in message_history_period: @@ -302,7 +308,9 @@ async def user_stats(self, ctx: TeXBotApplicationContext) -> None: x_label="Channel Name", y_label=( f"""Number of Messages Sent (in the past { - amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day") + amount_of_time_formatter( + settings.commands.stats.lookback_period.days, "day" + ) })""" ), title=( @@ -347,7 +355,7 @@ async def left_member_stats(self, ctx: TeXBotApplicationContext) -> None: } role_name: str - for role_name in settings["STATISTICS_ROLES"]: + for role_name in settings.commands.stats.displayed_roles: if discord.utils.get(main_guild.roles, name=role_name): left_member_counts[f"@{role_name}"] = 0 diff --git a/cogs/stats/counts.py b/cogs/stats/counts.py index 5e7d91593..6ee1ab644 100644 --- a/cogs/stats/counts.py +++ b/cogs/stats/counts.py @@ -20,12 +20,12 @@ async def get_channel_message_counts(channel: discord.TextChannel) -> Mapping[st message_counts: dict[str, int] = {"Total": 0} role_name: str - for role_name in settings["STATISTICS_ROLES"]: + for role_name in settings.commands.stats.displayed_roles: if discord.utils.get(channel.guild.roles, name=role_name): message_counts[f"@{role_name}"] = 0 message_history_period: AsyncIterable[discord.Message] = channel.history( - after=discord.utils.utcnow() - settings["STATISTICS_DAYS"] + after=discord.utils.utcnow() - settings.commands.stats.lookback_period ) message: discord.Message async for message in message_history_period: @@ -72,7 +72,7 @@ async def get_server_message_counts( message_counts: dict[str, dict[str, int]] = {"roles": {"Total": 0}, "channels": {}} role_name: str - for role_name in settings["STATISTICS_ROLES"]: + for role_name in settings.commands.stats.displayed_roles: if discord.utils.get(guild.roles, name=role_name): message_counts["roles"][f"@{role_name}"] = 0 @@ -87,7 +87,7 @@ async def get_server_message_counts( message_counts["channels"][f"#{channel.name}"] = 0 message_history_period: AsyncIterable[discord.Message] = channel.history( - after=discord.utils.utcnow() - settings["STATISTICS_DAYS"] + after=discord.utils.utcnow() - settings.commands.stats.lookback_period ) message: discord.Message async for message in message_history_period: diff --git a/cogs/strike.py b/cogs/strike.py index 13756b41d..b6a51636a 100644 --- a/cogs/strike.py +++ b/cogs/strike.py @@ -78,7 +78,7 @@ async def perform_moderation_action( if strikes == 1: await strike_user.timeout_for( - datetime.timedelta(hours=24), reason=MODERATION_ACTION_REASON + settings.commands.strike.timeout_duration, reason=MODERATION_ACTION_REASON ) elif strikes == 2: @@ -241,6 +241,17 @@ class BaseStrikeCog(TeXBotBaseCog): async def _send_strike_user_message( self, strike_user: discord.abc.Messageable, member_strikes: DiscordMemberStrikes ) -> None: + # NOTE: The link to the moderation document is optional, so the sentence pointing + # at it is left out entirely rather than sent holding a link that goes nowhere. + MODERATION_POLICY_MESSAGE: Final[str] = ( + f"To find what moderation action corresponds to which strike level, " + f"you can view " + f"the {self.bot.group_short_name} Discord server moderation document " + f"[here](<{settings.community_group.links.moderation_policy}>)\n" + if settings.community_group.links.moderation_policy is not None + else "" + ) + try: await strike_user.send( "Hi, a recent incident occurred in which you may have broken one or more of " @@ -248,10 +259,8 @@ async def _send_strike_user_message( "We have increased the number of strikes associated with your account " f"to {min(3, member_strikes.strikes)} and " "the corresponding moderation action will soon be applied to you. " - "To find what moderation action corresponds to which strike level, " - "you can view " - f"the {self.bot.group_short_name} Discord server moderation document " - f"[here](<{settings.MODERATION_DOCUMENT_URL}>)\nPlease ensure you have read " + f"{MODERATION_POLICY_MESSAGE}" + "Please ensure you have read " f"the rules in {await self.bot.get_mention_string(self.bot.rules_channel)} so " "that your future behaviour adheres to them." f"{ @@ -458,7 +467,7 @@ async def get_confirmation_message_channel( This is based upon the STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION config setting value. """ - if settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"] == "DM": + if settings.commands.strike.performed_manually_warning_location == "DM": if user.bot: fetch_log_channel_error: RuntimeError try: @@ -495,12 +504,12 @@ async def get_confirmation_message_channel( guild_confirmation_message_channel: discord.TextChannel | None = discord.utils.get( self.bot.main_guild.text_channels, - name=settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"], + name=settings.commands.strike.performed_manually_warning_location, ) if not guild_confirmation_message_channel: CHANNEL_DOES_NOT_EXIST_MESSAGE: Final[str] = ( "The channel " - f"""{settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"]!r} """ + f"""{settings.commands.strike.performed_manually_warning_location!r} """ "does not exist, so cannot be used as the location " "for sending manual-moderation warning messages" ) @@ -1023,14 +1032,24 @@ async def _send_message_to_committee( self, ctx: TeXBotApplicationContext, message: discord.Message ) -> None: """Send a provided message to committee channels.""" - discord_channel: discord.TextChannel | None = discord.utils.get( + destination_channel: discord.TextChannel | None = discord.utils.get( self.bot.main_guild.text_channels, - name="discord", # TODO: Make this user-configurable # noqa: FIX002 + name=settings.commands.strike.reported_message_destination_channel, ) - if not discord_channel: + if not destination_channel: + logger.warning( + "Reported messages cannot be sent to the configured channel %r, " + "because no channel with that name exists.", + settings.commands.strike.reported_message_destination_channel, + ) await self.command_send_error( - ctx, message="Could not find the `#discord` channel in the main guild!" + ctx, + message=( + "Could not find the " + f"`#{settings.commands.strike.reported_message_destination_channel}` " + "channel in the main guild!" + ), ) return @@ -1068,7 +1087,7 @@ async def _send_message_to_committee( if attachment_type and "image" in attachment_type: embed_image = message.attachments[0].url - await discord_channel.send( + await destination_channel.send( content=( f"{ctx.user.mention} reported a message from {message.author.mention} " f"in { diff --git a/cogs/write_roles.py b/cogs/write_roles.py index b9380cd7b..f4ed5467e 100644 --- a/cogs/write_roles.py +++ b/cogs/write_roles.py @@ -7,7 +7,7 @@ import discord from utils import CommandChecks, TeXBotBaseCog -lazy from config import settings +lazy from config import messages lazy from utils import TeXBotApplicationContext @@ -30,7 +30,7 @@ async def write_roles(self, ctx: TeXBotApplicationContext) -> None: roles_channel: discord.TextChannel = await self.bot.roles_channel roles_message: str - for roles_message in settings["ROLES_MESSAGES"]: + for roles_message in messages.roles_messages: await roles_channel.send( roles_message.replace("", self.bot.group_short_name) ) diff --git a/config.py b/config.py deleted file mode 100644 index 98383ed82..000000000 --- a/config.py +++ /dev/null @@ -1,1050 +0,0 @@ -""" -Contains settings values and import and setup functions. - -Settings values are imported from the .env file or the current environment variables. -These values are used to configure the functionality of the bot at run-time. -""" - -__all__: Sequence[str] = ( - "DEFAULT_STATISTICS_ROLES", - "FALSE_VALUES", - "LOG_LEVEL_CHOICES", - "TRUE_VALUES", - "VALID_SEND_INTRODUCTION_REMINDERS_VALUES", - "run_setup", - "settings", -) - -import abc -import functools -import logging -from pathlib import Path -from typing import final -lazy import datetime -lazy import importlib -lazy import json -lazy import os -lazy import re -lazy from collections.abc import Iterable, Mapping, Sequence -lazy from collections.abc import Set as AbstractSet -lazy from logging import Logger -lazy from typing import IO, Any, ClassVar, Final, LiteralString - -lazy import dotenv -lazy import validators -lazy from discord_logging.handler import DiscordHandler - -lazy from exceptions import ( - ImproperlyConfiguredError, - MessagesJSONFileMissingKeyError, - MessagesJSONFileValueError, -) - -PROJECT_ROOT: Final[Path] = Path(__file__).parent.resolve() - -TRUE_VALUES: Final[AbstractSet[LiteralString]] = {"true", "1", "t", "y", "yes", "on"} -FALSE_VALUES: Final[AbstractSet[LiteralString]] = {"false", "0", "f", "n", "no", "off"} -VALID_SEND_INTRODUCTION_REMINDERS_VALUES: Final[AbstractSet[LiteralString]] = ( - {"once", "interval"} | TRUE_VALUES | FALSE_VALUES -) -DEFAULT_STATISTICS_ROLES: Final[AbstractSet[LiteralString]] = { - "Committee", - "Committee-Elect", - "Student Rep", - "Member", - "Guest", - "Server Booster", - "Foundation Year", - "First Year", - "Second Year", - "Final Year", - "Year In Industry", - "Year Abroad", - "PGT", - "PGR", - "Alumnus/Alumna", - "Postdoc", - "Quiz Victor", -} -LOG_LEVEL_CHOICES: Final[Sequence[LiteralString]] = ( - "DEBUG", - "INFO", - "WARNING", - "ERROR", - "CRITICAL", -) - -logger: Final[Logger] = logging.getLogger("TeX-Bot") -discord_logger: Final[Logger] = logging.getLogger("discord") - - -class Settings(abc.ABC): - """ - Settings class that provides access to all settings values. - - Settings values can be accessed via key (like a dictionary) or via class attribute. - """ - - _is_env_variables_setup: ClassVar[bool] - _settings: ClassVar[dict[str, object]] - - @classmethod - def get_invalid_settings_key_message(cls, item: str) -> str: - """Return the message to state that the given settings key is invalid.""" - return f"{item!r} is not a valid settings key." - - def __getattr__(self, item: str) -> Any: # type: ignore[explicit-any] # noqa: ANN401 - """Retrieve settings value by attribute lookup.""" - MISSING_ATTRIBUTE_MESSAGE: Final[str] = ( - f"{type(self).__name__!r} object has no attribute {item!r}" - ) - - if ( - "_pytest" in item or item in ("__bases__", "__test__") - ): # NOTE: Overriding __getattr__() leads to many edge-case issues where external libraries will attempt to call getattr() with peculiar values - raise AttributeError(MISSING_ATTRIBUTE_MESSAGE) - - if not self._is_env_variables_setup: - self._setup_env_variables() - - if item in self._settings: - return self._settings[item] - - if re.fullmatch(pattern=r"\A[A-Z](?:[A-Z_]*[A-Z])?\Z", string=item): - INVALID_SETTINGS_KEY_MESSAGE: Final[str] = self.get_invalid_settings_key_message( - item - ) - raise AttributeError(INVALID_SETTINGS_KEY_MESSAGE) - - raise AttributeError(MISSING_ATTRIBUTE_MESSAGE) - - def __getitem__(self, item: str) -> Any: # type: ignore[explicit-any] # noqa: ANN401 - """Retrieve settings value by key lookup.""" - attribute_not_exist_error: AttributeError - try: - return getattr(self, item) - except AttributeError as attribute_not_exist_error: - key_error_message: str = item - - if self.get_invalid_settings_key_message(item) in str(attribute_not_exist_error): - key_error_message = str(attribute_not_exist_error) - - raise KeyError(key_error_message) from None - - @staticmethod - def _setup_console_logging() -> None: - raw_console_log_level: str = ( - os.getenv("CONSOLE_LOG_LEVEL", default="INFO").upper().strip() - ) - - if raw_console_log_level not in LOG_LEVEL_CHOICES: - INVALID_LOG_LEVEL_MESSAGE: Final[str] = f"CONSOLE_LOG_LEVEL must be one of { - ','.join( - f'{log_level_choice!r}' for log_level_choice in LOG_LEVEL_CHOICES[:-1] - ) - } or {LOG_LEVEL_CHOICES[-1]!r}." - raise ImproperlyConfiguredError(INVALID_LOG_LEVEL_MESSAGE) - - logger.setLevel(getattr(logging, raw_console_log_level)) - - console_logging_handler: logging.Handler = logging.StreamHandler() - console_logging_handler.setFormatter( - logging.Formatter("{asctime} | {name} | {levelname:^8} - {message}", style="{") - ) - - logger.addHandler(console_logging_handler) - logger.propagate = False - - @staticmethod - def _setup_discord_log_level() -> None: - raw_discord_log_level: str = os.getenv("DISCORD_LOG_LEVEL", default="").upper().strip() - - if not raw_discord_log_level: - logger.debug("DISCORD_LOG_LEVEL is not set, skipping Discord logging setup.") - return - - if raw_discord_log_level not in LOG_LEVEL_CHOICES: - INVALID_LOG_LEVEL_MESSAGE: Final[str] = ( - "DISCORD_LOG_LEVEL must be one of " - f"{ - ','.join( - f'{log_level_choice!r}' for log_level_choice in LOG_LEVEL_CHOICES[:-1] - ) - } or {LOG_LEVEL_CHOICES[-1]!r}" - ) - raise ImproperlyConfiguredError(INVALID_LOG_LEVEL_MESSAGE) - - discord_logger.setLevel(getattr(logging, raw_discord_log_level)) - - discord_log_handler: logging.Handler = logging.FileHandler( - filename="discord.log", encoding="utf-8", mode="a" - ) - discord_log_handler.setFormatter( - logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s") - ) - - discord_logger.addHandler(discord_log_handler) - discord_logger.propagate = False - - @classmethod - def _setup_discord_bot_token(cls) -> None: - raw_discord_bot_token: str = os.getenv("DISCORD_BOT_TOKEN", default="").strip() - - if not raw_discord_bot_token or not re.fullmatch( - pattern=r"\A([A-Za-z0-9_-]{24,26})\.([A-Za-z0-9_-]{6})\.([A-Za-z0-9_-]{27,38})\Z", - string=raw_discord_bot_token, - ): - INVALID_DISCORD_BOT_TOKEN_MESSAGE: Final[str] = ( - "DISCORD_BOT_TOKEN must be set to a valid Discord bot token " # noqa: S105 - "(see https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts)." - ) - raise ImproperlyConfiguredError(INVALID_DISCORD_BOT_TOKEN_MESSAGE) - - cls._settings["DISCORD_BOT_TOKEN"] = raw_discord_bot_token - - @classmethod - def _setup_discord_log_channel_webhook(cls) -> Logger: - raw_discord_log_channel_webhook_url: str = os.getenv( - "DISCORD_LOG_CHANNEL_WEBHOOK_URL", default="" - ).strip() - - if not raw_discord_log_channel_webhook_url: - cls._settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"] = None - return logging.getLogger("_temp_webhook_config") - - if not validators.url( - raw_discord_log_channel_webhook_url - ) or not raw_discord_log_channel_webhook_url.startswith( - "https://discord.com/api/webhooks/" - ): - INVALID_DISCORD_LOG_CHANNEL_WEBHOOK_URL_MESSAGE: Final[str] = ( - "DISCORD_LOG_CHANNEL_WEBHOOK_URL must be a valid webhook URL " - "that points to a discord channel where logs should be displayed." - ) - raise ImproperlyConfiguredError(INVALID_DISCORD_LOG_CHANNEL_WEBHOOK_URL_MESSAGE) - - webhook_config_logger: Logger = logging.getLogger("_temp_webhook_config") - - discord_logging_handler: logging.Handler = DiscordHandler( - service_name="TeX-Bot", webhook_url=raw_discord_log_channel_webhook_url - ) - - discord_logging_handler.setLevel(logging.WARNING) - - discord_logging_handler.setFormatter( - logging.Formatter("{levelname} | {message}", style="{") - ) - - webhook_config_logger.addHandler(discord_logging_handler) - - cls._settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"] = raw_discord_log_channel_webhook_url - - return webhook_config_logger - - @classmethod - def _setup_discord_guild_id(cls) -> None: - raw_discord_guild_id: str = os.getenv("DISCORD_GUILD_ID", default="").strip() - - if not raw_discord_guild_id or not re.fullmatch( - pattern=r"\A\d{17,20}\Z", string=raw_discord_guild_id - ): - INVALID_DISCORD_GUILD_ID_MESSAGE: Final[str] = ( - "DISCORD_GUILD_ID must be a valid Discord guild ID " - "(see https://docs.pycord.dev/en/stable/api/abcs.html#discord.abc.Snowflake.id)." - ) - raise ImproperlyConfiguredError(INVALID_DISCORD_GUILD_ID_MESSAGE) - - cls._settings["_DISCORD_MAIN_GUILD_ID"] = int(raw_discord_guild_id) - - @classmethod - def _setup_group_full_name(cls) -> None: - raw_group_full_name: str = os.getenv("GROUP_NAME", default="").strip() - - if not raw_group_full_name: - cls._settings["_GROUP_FULL_NAME"] = None - return - - if not re.fullmatch( - pattern=r"\A[A-Za-z0-9 '&!?:,.#%\"-]+\Z", string=raw_group_full_name - ): - INVALID_GROUP_FULL_NAME: Final[str] = ( - "GROUP_NAME must not contain any invalid characters." - ) - raise ImproperlyConfiguredError(INVALID_GROUP_FULL_NAME) - - cls._settings["_GROUP_FULL_NAME"] = raw_group_full_name - - @classmethod - def _setup_group_short_name(cls) -> None: - raw_group_short_name: str = os.getenv("GROUP_SHORT_NAME", default="").strip() - - if not raw_group_short_name: - cls._settings["_GROUP_SHORT_NAME"] = None - return - - if not re.fullmatch( - pattern=r"\A[A-Za-z0-9'&!?:,.#%\"-]+\Z", string=raw_group_short_name - ): - INVALID_GROUP_SHORT_NAME: Final[str] = ( - "GROUP_SHORT_NAME must not contain any invalid characters." - ) - raise ImproperlyConfiguredError(INVALID_GROUP_SHORT_NAME) - - cls._settings["_GROUP_SHORT_NAME"] = raw_group_short_name - - @classmethod - def _setup_purchase_membership_url(cls) -> None: - raw_purchase_membership_url: str = os.getenv( - "PURCHASE_MEMBERSHIP_URL", default="" - ).strip() - - if not raw_purchase_membership_url: - cls._settings["PURCHASE_MEMBERSHIP_URL"] = None - return - - if not raw_purchase_membership_url.startswith("https://"): - if "://" in raw_purchase_membership_url: - INVALID_PURCHASE_MEMBERSHIP_URL_PROTOCOL_MESSAGE: Final[str] = ( - "Only HTTPS is supported as a protocol for PURCHASE_MEMBERSHIP_URL." - ) - raise ImproperlyConfiguredError( - INVALID_PURCHASE_MEMBERSHIP_URL_PROTOCOL_MESSAGE - ) - - raw_purchase_membership_url = "https://" + raw_purchase_membership_url - logger.warning( - "PURCHASE_MEMBERSHIP_URL was missing a URL protocol. " - "Please ensure all URLs are valid HTTPS URLs." - ) - - if not validators.url(raw_purchase_membership_url): - INVALID_PURCHASE_MEMBERSHIP_URL_MESSAGE: Final[str] = ( - "PURCHASE_MEMBERSHIP_URL must be a valid URL." - ) - raise ImproperlyConfiguredError(INVALID_PURCHASE_MEMBERSHIP_URL_MESSAGE) - - cls._settings["PURCHASE_MEMBERSHIP_URL"] = raw_purchase_membership_url - - @classmethod - def _setup_membership_perks_url(cls) -> None: - raw_membership_perks_url: str = os.getenv("MEMBERSHIP_PERKS_URL", default="").strip() - - if not raw_membership_perks_url: - cls._settings["MEMBERSHIP_PERKS_URL"] = None - return - - if not raw_membership_perks_url.startswith("https://"): - if "://" in raw_membership_perks_url: - INVALID_MEMBERSHIP_PERKS_URL_PROTOCOL_MESSAGE: Final[str] = ( - "Only HTTPS is supported as a protocol for MEMBERSHIP_PERKS_URL." - ) - raise ImproperlyConfiguredError(INVALID_MEMBERSHIP_PERKS_URL_PROTOCOL_MESSAGE) - - raw_membership_perks_url = "https://" + raw_membership_perks_url - logger.warning( - "MEMBERSHIP_PERKS_URL was missing a URL protocol. " - "Please ensure all URLs are valid HTTPS URLs." - ) - - if not validators.url(raw_membership_perks_url): - INVALID_MEMBERSHIP_PERKS_URL_MESSAGE: Final[str] = ( - "MEMBERSHIP_PERKS_URL must be a valid URL." - ) - raise ImproperlyConfiguredError(INVALID_MEMBERSHIP_PERKS_URL_MESSAGE) - - cls._settings["MEMBERSHIP_PERKS_URL"] = raw_membership_perks_url - - @classmethod - def _setup_custom_discord_invite_url(cls) -> None: - raw_custom_discord_invite_url: str = os.getenv( - "CUSTOM_DISCORD_INVITE_URL", default="" - ).strip() - - if not raw_custom_discord_invite_url: - cls._settings["CUSTOM_DISCORD_INVITE_URL"] = None - return - - if not raw_custom_discord_invite_url.startswith("https://"): - if "://" in raw_custom_discord_invite_url: - INVALID_CUSTOM_DISCORD_INVITE_URL_PROTOCOL_MESSAGE: Final[str] = ( - "Only HTTPS is supported as a protocol for CUSTOM_DISCORD_INVITE_URL." - ) - raise ImproperlyConfiguredError( - INVALID_CUSTOM_DISCORD_INVITE_URL_PROTOCOL_MESSAGE - ) - - raw_custom_discord_invite_url = "https://" + raw_custom_discord_invite_url - logger.warning( - "CUSTOM_DISCORD_INVITE_URL was missing a URL protocol. " - "Please ensure all URLs are valid HTTPS URLs." - ) - - if not validators.url(raw_custom_discord_invite_url): - INVALID_CUSTOM_DISCORD_INVITE_URL_MESSAGE: Final[str] = ( - "CUSTOM_DISCORD_INVITE_URL must be a valid URL." - ) - raise ImproperlyConfiguredError(INVALID_CUSTOM_DISCORD_INVITE_URL_MESSAGE) - - cls._settings["CUSTOM_DISCORD_INVITE_URL"] = raw_custom_discord_invite_url - - @classmethod - def _setup_ping_command_easter_egg_probability(cls) -> None: - raw_ping_command_easter_egg_probability_string: str = os.getenv( - "PING_COMMAND_EASTER_EGG_PROBABILITY", default="" - ).strip() - - if not raw_ping_command_easter_egg_probability_string: - cls._settings["PING_COMMAND_EASTER_EGG_PROBABILITY"] = 1 - return - - INVALID_PING_COMMAND_EASTER_EGG_PROBABILITY_MESSAGE: Final[str] = ( - "PING_COMMAND_EASTER_EGG_PROBABILITY must be a float between & including 0 to 1." - ) - - e: ValueError - try: - raw_ping_command_easter_egg_probability: float = 100 * float( - raw_ping_command_easter_egg_probability_string - ) - except ValueError as e: - raise ( - ImproperlyConfiguredError(INVALID_PING_COMMAND_EASTER_EGG_PROBABILITY_MESSAGE) - ) from e - - if not 0 <= raw_ping_command_easter_egg_probability <= 100: - raise ImproperlyConfiguredError( - INVALID_PING_COMMAND_EASTER_EGG_PROBABILITY_MESSAGE - ) - - cls._settings["PING_COMMAND_EASTER_EGG_PROBABILITY"] = ( - raw_ping_command_easter_egg_probability - ) - - @classmethod - @functools.lru_cache(maxsize=5) - def _get_messages_dict(cls, raw_messages_file_path: str | None) -> Mapping[str, object]: - JSON_DECODING_ERROR_MESSAGE: Final[str] = ( - "Messages JSON file must contain a JSON string that can be decoded " - "into a Python dict object." - ) - - messages_file_path: Path = ( - Path(raw_messages_file_path.strip()) - if raw_messages_file_path - else PROJECT_ROOT / Path("messages.json") - ) - - if not messages_file_path.is_file(): - MESSAGES_FILE_PATH_DOES_NOT_EXIST_MESSAGE: Final[str] = ( - "MESSAGES_FILE_PATH must be a path to a file that exists." - ) - raise ImproperlyConfiguredError(MESSAGES_FILE_PATH_DOES_NOT_EXIST_MESSAGE) - - messages_file: IO[str] - with messages_file_path.open(encoding="utf8") as messages_file: - e: json.JSONDecodeError - try: - messages_dict: object = json.load(messages_file) - except json.JSONDecodeError as e: - raise ImproperlyConfiguredError(JSON_DECODING_ERROR_MESSAGE) from e - - if not isinstance(messages_dict, Mapping): - raise ImproperlyConfiguredError(JSON_DECODING_ERROR_MESSAGE) - - return messages_dict - - @classmethod - def _setup_welcome_messages(cls) -> None: - messages_dict: Mapping[str, object] = cls._get_messages_dict( - os.getenv("MESSAGES_FILE_PATH") - ) - - if "welcome_messages" not in messages_dict: - raise MessagesJSONFileMissingKeyError(missing_key="welcome_messages") - - WELCOME_MESSAGES_KEY_IS_VALID: Final[bool] = bool( - isinstance(messages_dict["welcome_messages"], Iterable) - and messages_dict["welcome_messages"] - ) - if not WELCOME_MESSAGES_KEY_IS_VALID: - raise MessagesJSONFileValueError( - dict_key="welcome_messages", invalid_value=messages_dict["welcome_messages"] - ) - - cls._settings["WELCOME_MESSAGES"] = set(messages_dict["welcome_messages"]) # type: ignore[call-overload] - - @classmethod - def _setup_roles_messages(cls) -> None: - messages_dict: Mapping[str, object] = cls._get_messages_dict( - os.getenv("MESSAGES_FILE_PATH") - ) - - if "roles_messages" not in messages_dict: - raise MessagesJSONFileMissingKeyError(missing_key="roles_messages") - - ROLES_MESSAGES_KEY_IS_VALID: Final[bool] = isinstance( - messages_dict["roles_messages"], Iterable - ) and bool(messages_dict["roles_messages"]) - if not ROLES_MESSAGES_KEY_IS_VALID: - raise MessagesJSONFileValueError( - dict_key="roles_messages", invalid_value=messages_dict["roles_messages"] - ) - - cls._settings["ROLES_MESSAGES"] = set(messages_dict["roles_messages"]) # type: ignore[call-overload] - - @classmethod - def _setup_organisation_id(cls) -> None: - raw_organisation_id: str = os.getenv("ORGANISATION_ID", default="").strip() - - if not raw_organisation_id or not re.fullmatch( - pattern=r"\A\d{4,5}\Z", string=raw_organisation_id - ): - INVALID_ORGANISATION_ID_MESSAGE: Final[str] = ( - "ORGANISATION_ID must be an integer 4 to 5 digits long." - ) - raise ImproperlyConfiguredError(INVALID_ORGANISATION_ID_MESSAGE) - - cls._settings["ORGANISATION_ID"] = raw_organisation_id - - @classmethod - def _setup_su_platform_access_cookie(cls) -> None: - raw_su_platform_access_cookie: str = os.getenv( - "SU_PLATFORM_ACCESS_COOKIE", - default="", - ).strip() - - if not raw_su_platform_access_cookie or not re.fullmatch( - pattern=r"\A[\w-]{512,1024}\Z", string=raw_su_platform_access_cookie - ): - INVALID_SU_PLATFORM_ACCESS_COOKIE_MESSAGE: Final[str] = ( - "SU_PLATFORM_ACCESS_COOKIE must be a valid .AspNet.SharedCookie cookie." - ) - raise ImproperlyConfiguredError(INVALID_SU_PLATFORM_ACCESS_COOKIE_MESSAGE) - - cls._settings["SU_PLATFORM_ACCESS_COOKIE"] = raw_su_platform_access_cookie - - @classmethod - def _setup_auto_su_platform_access_cookie_checking(cls) -> None: - raw_auto_auth_session_cookie_checking: str = ( - os.getenv("AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING", default="False") - .lower() - .strip() - ) - - if raw_auto_auth_session_cookie_checking not in TRUE_VALUES | FALSE_VALUES: - INVALID_AUTO_AUTH_CHECKING_MESSAGE: Final[str] = ( - "AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING must be a boolean value." - ) - raise ImproperlyConfiguredError(INVALID_AUTO_AUTH_CHECKING_MESSAGE) - - cls._settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING"] = ( - raw_auto_auth_session_cookie_checking in TRUE_VALUES - ) - - @classmethod - def _setup_auto_su_platform_access_cookie_checking_interval(cls) -> None: - if "AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING" not in cls._settings: - INVALID_SETUP_ORDER_MESSAGE: Final[str] = ( - "Invalid setup order: AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING must be set up " - "before AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL can be set up." - ) - raise RuntimeError(INVALID_SETUP_ORDER_MESSAGE) - - if not cls._settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING"]: - cls._settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL"] = {"hours": 24} - return - - raw_auto_su_platform_access_cookie_checking_interval: re.Match[str] | None = ( - re.fullmatch( - pattern=r"\A(?:(?P(?:\d*\.)?\d+)s)?(?:(?P(?:\d*\.)?\d+)m)?(?:(?P(?:\d*\.)?\d+)h)?\Z", - string=( - os.getenv( - "AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL", default="24h" - ) - .strip() - .lower() - .replace(" ", "") - ), - ) - ) - - if not raw_auto_su_platform_access_cookie_checking_interval: - INVALID_AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL_MESSAGE: Final[str] = ( - "AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL must contain the delay " - "in any combination of seconds, minutes or hours." - ) - logger.debug(raw_auto_su_platform_access_cookie_checking_interval) - raise ImproperlyConfiguredError( - INVALID_AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL_MESSAGE - ) - - raw_timedelta_auto_su_platform_access_cookie_checking_interval: Mapping[str, float] = ( - frozendict( - { - key: float(stripped_value) - for key, value in ( - raw_auto_su_platform_access_cookie_checking_interval.groupdict().items() - ) - if value and (stripped_value := value.strip()) - } - ) - ) - - if ( - datetime.timedelta( - **raw_timedelta_auto_su_platform_access_cookie_checking_interval - ).total_seconds() - <= 3 - ): - TOO_SMALL_AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL_MESSAGE: Final[str] = ( - "AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL " - "must be greater than 3 seconds." - ) - raise ImproperlyConfiguredError( - TOO_SMALL_AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL_MESSAGE, - ) - - cls._settings["AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL"] = ( - raw_timedelta_auto_su_platform_access_cookie_checking_interval - ) - - @classmethod - def _setup_send_introduction_reminders(cls) -> None: - raw_send_introduction_reminders: str | bool = ( - os.getenv("SEND_INTRODUCTION_REMINDERS", default="Once").lower().strip() - ) - - if raw_send_introduction_reminders not in VALID_SEND_INTRODUCTION_REMINDERS_VALUES: - INVALID_SEND_INTRODUCTION_REMINDERS_MESSAGE: Final[str] = ( - 'SEND_INTRODUCTION_REMINDERS must be one of: "Once", "Interval" or "False".' - ) - raise ImproperlyConfiguredError(INVALID_SEND_INTRODUCTION_REMINDERS_MESSAGE) - - if raw_send_introduction_reminders in TRUE_VALUES: - raw_send_introduction_reminders = "once" - - elif raw_send_introduction_reminders not in ("once", "interval"): - raw_send_introduction_reminders = False - - cls._settings["SEND_INTRODUCTION_REMINDERS"] = raw_send_introduction_reminders - - @classmethod - def _setup_send_introduction_reminders_delay(cls) -> None: - if "SEND_INTRODUCTION_REMINDERS" not in cls._settings: - INVALID_SETUP_ORDER_MESSAGE: Final[str] = ( - "Invalid setup order: SEND_INTRODUCTION_REMINDERS must be set up " - "before SEND_INTRODUCTION_REMINDERS_DELAY can be set up." - ) - raise RuntimeError(INVALID_SETUP_ORDER_MESSAGE) - - raw_send_introduction_reminders_delay: re.Match[str] | None = re.fullmatch( - pattern=r"\A(?:(?P(?:\d*\.)?\d+)s)?(?:(?P(?:\d*\.)?\d+)m)?(?:(?P(?:\d*\.)?\d+)h)?(?:(?P(?:\d*\.)?\d+)d)?(?:(?P(?:\d*\.)?\d+)w)?\Z", - string=( - os.getenv("SEND_INTRODUCTION_REMINDERS_DELAY", default="40h") - .strip() - .lower() - .replace(" ", "") - ), - ) - - raw_timedelta_send_introduction_reminders_delay: datetime.timedelta = ( - datetime.timedelta() - ) - - if cls._settings["SEND_INTRODUCTION_REMINDERS"]: - if not raw_send_introduction_reminders_delay: - INVALID_SEND_INTRODUCTION_REMINDERS_DELAY_MESSAGE: Final[str] = ( - "SEND_INTRODUCTION_REMINDERS_DELAY must contain the delay " - "in any combination of seconds, minutes, hours, days or weeks." - ) - raise ImproperlyConfiguredError( - INVALID_SEND_INTRODUCTION_REMINDERS_DELAY_MESSAGE - ) - - raw_timedelta_send_introduction_reminders_delay = datetime.timedelta( - **{ - key: float(value) - for key, value in raw_send_introduction_reminders_delay.groupdict().items() - if value - } - ) - - if raw_timedelta_send_introduction_reminders_delay < datetime.timedelta(days=1): - TOO_SMALL_SEND_INTRODUCTION_REMINDERS_DELAY_MESSAGE: Final[str] = ( - "SEND_INTRODUCTION_REMINDERS_DELAY must be longer than or equal to 1 day." - ) - raise ImproperlyConfiguredError( - TOO_SMALL_SEND_INTRODUCTION_REMINDERS_DELAY_MESSAGE - ) - - cls._settings["SEND_INTRODUCTION_REMINDERS_DELAY"] = ( - raw_timedelta_send_introduction_reminders_delay - ) - - @classmethod - def _setup_send_introduction_reminders_interval(cls) -> None: - if "SEND_INTRODUCTION_REMINDERS" not in cls._settings: - INVALID_SETUP_ORDER_MESSAGE: Final[str] = ( - "Invalid setup order: SEND_INTRODUCTION_REMINDERS must be set up " - "before SEND_INTRODUCTION_REMINDERS_INTERVAL can be set up." - ) - raise RuntimeError(INVALID_SETUP_ORDER_MESSAGE) - - raw_send_introduction_reminders_interval: re.Match[str] | None = re.fullmatch( - pattern=r"\A(?:(?P(?:\d*\.)?\d+)s)?(?:(?P(?:\d*\.)?\d+)m)?(?:(?P(?:\d*\.)?\d+)h)?\Z", - string=( - os.getenv("SEND_INTRODUCTION_REMINDERS_INTERVAL", default="6h") - .strip() - .lower() - .replace(" ", "") - ), - ) - - raw_timedelta_details_send_introduction_reminders_interval: Mapping[str, float] = ( - frozendict(hours=6) - ) - - if cls._settings["SEND_INTRODUCTION_REMINDERS"]: - if not raw_send_introduction_reminders_interval: - INVALID_SEND_INTRODUCTION_REMINDERS_INTERVAL_MESSAGE: Final[str] = ( - "SEND_INTRODUCTION_REMINDERS_INTERVAL must contain the interval " - "in any combination of seconds, minutes or hours." - ) - raise ImproperlyConfiguredError( - INVALID_SEND_INTRODUCTION_REMINDERS_INTERVAL_MESSAGE - ) - - raw_timedelta_details_send_introduction_reminders_interval = frozendict( - { - key: float(value) - for key, value in ( - raw_send_introduction_reminders_interval.groupdict().items() - ) - if value - } - ) - - if ( - datetime.timedelta( - **raw_timedelta_details_send_introduction_reminders_interval - ).total_seconds() - <= 3 - ): - TOO_SMALL_SEND_INTRODUCTION_REMINDERS_INTERVAL_MESSAGE: Final[str] = ( - "SEND_INTRODUCTION_REMINDERS_INTERVAL must be longer than 3 seconds." - ) - raise ImproperlyConfiguredError( - TOO_SMALL_SEND_INTRODUCTION_REMINDERS_INTERVAL_MESSAGE - ) - - cls._settings["SEND_INTRODUCTION_REMINDERS_INTERVAL"] = ( - raw_timedelta_details_send_introduction_reminders_interval - ) - - @classmethod - def _setup_send_get_roles_reminders(cls) -> None: - raw_send_get_roles_reminders: str = ( - os.getenv("SEND_GET_ROLES_REMINDERS", default="True").lower().strip() - ) - - if raw_send_get_roles_reminders not in TRUE_VALUES | FALSE_VALUES: - INVALID_SEND_GET_ROLES_REMINDERS_MESSAGE: Final[str] = ( - "SEND_GET_ROLES_REMINDERS must be a boolean value." - ) - raise ImproperlyConfiguredError(INVALID_SEND_GET_ROLES_REMINDERS_MESSAGE) - - cls._settings["SEND_GET_ROLES_REMINDERS"] = raw_send_get_roles_reminders in TRUE_VALUES - - @classmethod - def _setup_send_get_roles_reminders_delay(cls) -> None: - if "SEND_GET_ROLES_REMINDERS" not in cls._settings: - INVALID_SETUP_ORDER_MESSAGE: Final[str] = ( - "Invalid setup order: SEND_GET_ROLES_REMINDERS must be set up " - "before SEND_GET_ROLES_REMINDERS_DELAY can be set up." - ) - raise RuntimeError(INVALID_SETUP_ORDER_MESSAGE) - - raw_send_get_roles_reminders_delay: re.Match[str] | None = re.fullmatch( - pattern=r"\A(?:(?P(?:\d*\.)?\d+)s)?(?:(?P(?:\d*\.)?\d+)m)?(?:(?P(?:\d*\.)?\d+)h)?(?:(?P(?:\d*\.)?\d+)d)?(?:(?P(?:\d*\.)?\d+)w)?\Z", - string=( - os.getenv("SEND_GET_ROLES_REMINDERS_DELAY", default="40h") - .strip() - .lower() - .replace(" ", "") - ), - ) - - raw_timedelta_send_get_roles_reminders_delay: datetime.timedelta = datetime.timedelta() - - if cls._settings["SEND_GET_ROLES_REMINDERS"]: - if not raw_send_get_roles_reminders_delay: - INVALID_SEND_GET_ROLES_REMINDERS_DELAY_MESSAGE: Final[str] = ( - "SEND_GET_ROLES_REMINDERS_DELAY must contain the delay " - "in any combination of seconds, minutes, hours, days or weeks." - ) - raise ImproperlyConfiguredError(INVALID_SEND_GET_ROLES_REMINDERS_DELAY_MESSAGE) - - raw_timedelta_send_get_roles_reminders_delay = datetime.timedelta( - **{ - key: float(value) - for key, value in raw_send_get_roles_reminders_delay.groupdict().items() - if value - } - ) - - if raw_timedelta_send_get_roles_reminders_delay < datetime.timedelta(days=1): - TOO_SMALL_SEND_GET_ROLES_REMINDERS_DELAY_MESSAGE: Final[str] = ( - "SEND_GET_ROLES_REMINDERS_DELAY must be longer than or equal to 1 day." - ) - raise ImproperlyConfiguredError( - TOO_SMALL_SEND_GET_ROLES_REMINDERS_DELAY_MESSAGE - ) - - cls._settings["SEND_GET_ROLES_REMINDERS_DELAY"] = ( - raw_timedelta_send_get_roles_reminders_delay - ) - - @classmethod - def _setup_advanced_send_get_roles_reminders_interval(cls) -> None: - if "SEND_GET_ROLES_REMINDERS" not in cls._settings: - INVALID_SETUP_ORDER_MESSAGE: Final[str] = ( - "Invalid setup order: SEND_GET_ROLES_REMINDERS must be set up " - "before ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL can be set up." - ) - raise RuntimeError(INVALID_SETUP_ORDER_MESSAGE) - - raw_advanced_send_get_roles_reminders_interval: re.Match[str] | None = re.fullmatch( - pattern=r"\A(?:(?P(?:\d*\.)?\d+)s)?(?:(?P(?:\d*\.)?\d+)m)?(?:(?P(?:\d*\.)?\d+)h)?\Z", - string=( - os.getenv("ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL", default="24h") - .strip() - .lower() - .replace(" ", "") - ), - ) - - raw_timedelta_details_advanced_send_get_roles_reminders_interval: Mapping[ - str, float - ] = frozendict(hours=24) - - if cls._settings["SEND_GET_ROLES_REMINDERS"]: - if not raw_advanced_send_get_roles_reminders_interval: - INVALID_ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL_MESSAGE: Final[str] = ( - "ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL must contain the interval " - "in any combination of seconds, minutes or hours." - ) - raise ImproperlyConfiguredError( - INVALID_ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL_MESSAGE - ) - - raw_timedelta_details_advanced_send_get_roles_reminders_interval = { - key: float(value) - for key, value in ( - raw_advanced_send_get_roles_reminders_interval.groupdict().items() - ) - if value - } - - cls._settings["ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL"] = ( - raw_timedelta_details_advanced_send_get_roles_reminders_interval - ) - - @classmethod - def _setup_statistics_days(cls) -> None: - e: ValueError - try: - raw_statistics_days: float = float( - os.getenv("STATISTICS_DAYS", default="30").strip() - ) - except ValueError as e: - INVALID_STATISTICS_DAYS_MESSAGE: Final[str] = ( - "STATISTICS_DAYS must contain the statistics period in days." - ) - raise ImproperlyConfiguredError(INVALID_STATISTICS_DAYS_MESSAGE) from e - - if raw_statistics_days < 1: - TOO_SMALL_STATISTICS_DAYS_MESSAGE: Final[str] = ( - "STATISTICS_DAYS cannot be less than 1 day." - ) - raise ImproperlyConfiguredError(TOO_SMALL_STATISTICS_DAYS_MESSAGE) - - cls._settings["STATISTICS_DAYS"] = datetime.timedelta(days=raw_statistics_days) - - @classmethod - def _setup_statistics_roles(cls) -> None: - raw_statistics_roles: str = os.getenv("STATISTICS_ROLES", default="").strip() - - if not raw_statistics_roles: - cls._settings["STATISTICS_ROLES"] = DEFAULT_STATISTICS_ROLES - return - - statistics_roles: AbstractSet[str] = { - raw_statistics_role.strip() - for raw_statistics_role in raw_statistics_roles.split(",") - if raw_statistics_role.strip() - } - - cls._settings["STATISTICS_ROLES"] = statistics_roles or DEFAULT_STATISTICS_ROLES - - @classmethod - def _setup_membership_dependent_roles(cls) -> None: - raw_membership_dependent_roles: str = os.getenv( - "MEMBERSHIP_DEPENDENT_ROLES", default="" - ).strip() - - if not raw_membership_dependent_roles: - cls._settings["MEMBERSHIP_DEPENDENT_ROLES"] = frozenset() - return - - cls._settings["MEMBERSHIP_DEPENDENT_ROLES"] = frozenset( - raw_membership_dependent_role.strip() - for raw_membership_dependent_role in raw_membership_dependent_roles.split(",") - if raw_membership_dependent_role.strip() - ) - - @classmethod - def _setup_moderation_document_url(cls) -> None: - INVALID_MODERATION_DOCUMENT_URL_MESSAGE: Final[str] = ( - "MODERATION_DOCUMENT_URL must be a valid URL." - ) - - raw_moderation_document_url: str = ( - os.getenv("MODERATION_DOCUMENT_URL", default="").strip().lower() - ) - - if not raw_moderation_document_url: - raise ImproperlyConfiguredError(INVALID_MODERATION_DOCUMENT_URL_MESSAGE) - - if not raw_moderation_document_url.startswith("https://"): - if "://" in raw_moderation_document_url: - INVALID_MODERATION_DOCUMENT_URL_PROTOCOL_MESSAGE: Final[str] = ( - "Only HTTPS is supported as a protocol for MODERATION_DOCUMENT_URL." - ) - raise ImproperlyConfiguredError( - INVALID_MODERATION_DOCUMENT_URL_PROTOCOL_MESSAGE - ) - - raw_moderation_document_url = "https://" + raw_moderation_document_url - logger.warning( - "MODERATION_DOCUMENT_URL was missing a URL protocol. " - "Please ensure all URLs are valid HTTPS URLs." - ) - - if not validators.url(raw_moderation_document_url): - raise ImproperlyConfiguredError(INVALID_MODERATION_DOCUMENT_URL_MESSAGE) - - cls._settings["MODERATION_DOCUMENT_URL"] = raw_moderation_document_url - - @classmethod - def _setup_strike_performed_manually_warning_location(cls) -> None: - raw_strike_performed_manually_warning_location: str = os.getenv( - "MANUAL_MODERATION_WARNING_MESSAGE_LOCATION", default="DM" - ).strip() - - if not raw_strike_performed_manually_warning_location: - STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION_MESSAGE: Final[str] = ( - "MANUAL_MODERATION_WARNING_MESSAGE_LOCATION must be a valid name " - "of a channel in your group's Discord guild." - ) - raise ImproperlyConfiguredError(STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION_MESSAGE) - - cls._settings["STRIKE_PERFORMED_MANUALLY_WARNING_LOCATION"] = ( - raw_strike_performed_manually_warning_location - ) - - @classmethod - def _setup_auto_add_committee_to_threads(cls) -> None: - raw_auto_add_committee_to_threads: str = ( - os.getenv("AUTO_ADD_COMMITTEE_TO_THREADS", default="True").lower().strip() - ) - - if raw_auto_add_committee_to_threads not in TRUE_VALUES | FALSE_VALUES: - INVALID_AUTO_ADD_COMMITTEE_TO_THREADS_MESSAGE: Final[str] = ( - "AUTO_ADD_COMMITTEE_TO_THREADS must be a boolean value." - ) - raise ImproperlyConfiguredError(INVALID_AUTO_ADD_COMMITTEE_TO_THREADS_MESSAGE) - - cls._settings["AUTO_ADD_COMMITTEE_TO_THREADS"] = ( - raw_auto_add_committee_to_threads in TRUE_VALUES - ) - - @classmethod - def _setup_env_variables(cls) -> None: - """ - Load environment values into the settings dictionary. - - Environment values are loaded from the .env file/the current environment variables and - are only stored after the input values have been validated. - """ - if cls._is_env_variables_setup: - logger.warning("Environment variables have already been set up.") - return - - dotenv.load_dotenv() - - webhook_config_logger: Logger = cls._setup_discord_log_channel_webhook() - - try: - cls._setup_console_logging() - cls._setup_discord_log_level() - cls._setup_discord_bot_token() - cls._setup_discord_guild_id() - cls._setup_group_full_name() - cls._setup_group_short_name() - cls._setup_ping_command_easter_egg_probability() - cls._setup_welcome_messages() - cls._setup_roles_messages() - cls._setup_organisation_id() - cls._setup_su_platform_access_cookie() - cls._setup_auto_su_platform_access_cookie_checking() - cls._setup_auto_su_platform_access_cookie_checking_interval() - cls._setup_membership_perks_url() - cls._setup_purchase_membership_url() - cls._setup_custom_discord_invite_url() - cls._setup_send_introduction_reminders() - cls._setup_send_introduction_reminders_delay() - cls._setup_send_introduction_reminders_interval() - cls._setup_send_get_roles_reminders() - cls._setup_send_get_roles_reminders_delay() - cls._setup_advanced_send_get_roles_reminders_interval() - cls._setup_statistics_days() - cls._setup_statistics_roles() - cls._setup_membership_dependent_roles() - cls._setup_moderation_document_url() - cls._setup_strike_performed_manually_warning_location() - cls._setup_auto_add_committee_to_threads() - except ImproperlyConfiguredError as improper_config_error: - webhook_config_logger.error(improper_config_error.message) # noqa: TRY400 - raise improper_config_error from improper_config_error - - cls._is_env_variables_setup = True - - -def _settings_class_factory() -> type[Settings]: - @final - class RuntimeSettings(Settings): # noqa: CAR160 - """ - Settings class that provides access to all settings values. - - Settings values can be accessed via key (like a dictionary) or via class attribute. - """ - - _is_env_variables_setup: ClassVar[bool] = False - _settings: ClassVar[dict[str, object]] = {} - - return RuntimeSettings - - -settings: Final[Settings] = _settings_class_factory()() - - -def run_setup() -> None: - """Execute the required setup functions.""" - settings._setup_env_variables() # noqa: SLF001 - - logger.debug("Begin database setup") - - importlib.import_module("db") - importlib.import_module("django.core.management").call_command("migrate") - - logger.debug("Database setup completed") diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 000000000..9b6044e24 --- /dev/null +++ b/config/__init__.py @@ -0,0 +1,238 @@ +""" +Contains settings values and import & setup functions. + +Settings values are loaded from the `tex-bot-deployment.yaml` deployment configuration +file, validated against the schema declared within `config._schema`. These values +configure the functionality of TeX-Bot at run-time, and can be reloaded without +restarting TeX-Bot, except for those settings that require a restart. +""" + +import importlib +import logging +from typing import TYPE_CHECKING, NamedTuple + +from pydantic import TypeAdapter, ValidationError + +from exceptions import ( + ImproperlyConfiguredError, + InvalidSettingsFileError, + SettingsFileChangedError, + SettingsFileNotFoundError, + SettingsNotLoadedError, + SettingsValidationError, + UnknownSettingError, +) + +from ._accessor import SettingsAccessor +from ._document import SettingsDocument, get_settings_file_path +from ._editor import ( + SETTING_NAME_SEPARATOR, + documented_setting_names, + format_file_difference, + format_setting_value, + parse_setting_value, + setting_metadata, + validated_document_with_setting_removed, + validated_document_with_setting_set, +) +from ._logging import ( + apply_logging_settings, + relay_start_up_error_to_discord_log_channel, + set_discord_log_channel_identity, +) +from ._messages import MessagesAccessor +from ._schema import ConfigSettingMetadata, DiscordWebhookURL, get_settings_metadata + +if TYPE_CHECKING: + from collections.abc import Sequence + from collections.abc import Set as AbstractSet + from logging import Logger + from pathlib import Path + from typing import Final + + +__all__: Sequence[str] = ( + "SETTING_NAME_SEPARATOR", + "ConfigReloadResult", + "ConfigSettingMetadata", + "InvalidSettingsFileError", + "SettingsDocument", + "SettingsFileChangedError", + "SettingsFileNotFoundError", + "SettingsNotLoadedError", + "SettingsValidationError", + "UnknownSettingError", + "documented_setting_names", + "format_file_difference", + "format_setting_value", + "get_settings_file_path", + "get_settings_metadata", + "messages", + "reload_settings", + "run_setup", + "set_discord_log_channel_identity", + "set_setting", + "setting_metadata", + "settings", + "unset_setting", +) + + +logger: Final[Logger] = logging.getLogger("TeX-Bot") + +settings: Final[SettingsAccessor] = SettingsAccessor() + +messages: Final[MessagesAccessor] = MessagesAccessor() + + +class ConfigReloadResult(NamedTuple): + """The outcome of reloading the deployment configuration file.""" + + changed_settings: AbstractSet[str] + restart_required_settings: AbstractSet[str] + + +def reload_settings(file_path: Path | None = None) -> ConfigReloadResult: + """ + Reload the deployment configuration file, applying any settings that have changed. + + Returns the settings key paths whose values have changed, along with the subset of + those that cannot take effect until TeX-Bot is restarted. + + The configuration file is located afresh unless one is given explicitly. A change + written by `set_setting()` or `unset_setting()` names the file it was written into, + so that the change is always read back out of the file it was made to, rather than + out of whichever file would be located now. + + The currently loaded configuration is left untouched if the file cannot be read or + contains invalid settings. + """ + CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload(file_path) + + if any(changed_setting.startswith("logging:") for changed_setting in CHANGED_SETTINGS): + apply_logging_settings(settings.logging) + + return ConfigReloadResult( + changed_settings=CHANGED_SETTINGS, + # NOTE: Only a setting whose new value differs from the one TeX-Bot started with + # needs a restart. Changing one back to its start-up value needs no restart. + restart_required_settings=frozenset( + CHANGED_SETTINGS & settings.values_awaiting_restart.keys() + ), + ) + + +def _loaded_document() -> SettingsDocument | None: + """Return the configuration document currently loaded, if any configuration has been.""" + return settings.document if settings.is_loaded else None + + +def set_setting(setting_name: str, raw_value: str) -> ConfigReloadResult: + """ + Change a single setting within the configuration file, then apply the change. + + The new value is validated before the file is written, so a value that would be + rejected leaves both the file & the running configuration exactly as they were. + + Changing a file that has been edited by hand since it was last loaded is refused, + so that a change is only ever made against the configuration TeX-Bot is running. + + Returns the settings that changed as a result, along with the subset of those that + cannot take effect until TeX-Bot is restarted. + """ + UPDATED_DOCUMENT: Final[SettingsDocument] = validated_document_with_setting_set( + setting_name, parse_setting_value(setting_name, raw_value), _loaded_document() + ) + + UPDATED_DOCUMENT.write() + + return reload_settings(UPDATED_DOCUMENT.file_path) + + +def unset_setting(setting_name: str) -> ConfigReloadResult | None: + """ + Remove a single setting from the configuration file, then apply its removal. + + The setting returns to its default value. `None` is returned where the setting was + not written within the file to begin with, so nothing needed to be removed. + + Removing a setting that is required leaves the file untouched, because the + configuration that removing it would produce is not valid. Removing a setting from a + file that has been edited by hand since it was last loaded is likewise refused. + + Removing a setting that an optional section cannot be used without (such as + `logging:discord-channel:webhook-url`) removes the whole of that section with it. + """ + UPDATED_DOCUMENT: Final[SettingsDocument | None] = validated_document_with_setting_removed( + setting_name, _loaded_document() + ) + + if UPDATED_DOCUMENT is None: + return None + + UPDATED_DOCUMENT.write() + + return reload_settings(UPDATED_DOCUMENT.file_path) + + +def _webhook_url_written_within_file() -> str | None: + """ + Return the Discord log channel webhook URL written within the configuration file. + + Read from the file directly, rather than from the loaded settings, for use when + the configuration as a whole is not valid. `None` is returned where the file + cannot be read, or holds no webhook URL that is valid on its own. + """ + try: + raw_settings: object = SettingsDocument.load().raw + except SettingsFileNotFoundError, InvalidSettingsFileError, OSError: + return None + + key: str + for key in ("logging", "discord-channel", "webhook-url"): + if not isinstance(raw_settings, dict): + return None + + raw_settings = raw_settings.get(key) + + try: + return str(TypeAdapter(DiscordWebhookURL).validate_python(raw_settings)) + except ValidationError: + return None + + +def run_setup() -> None: + """ + Execute the setup functions required before TeX-Bot can be run. + + An error in the configuration that stops TeX-Bot from starting up is also sent to + the Discord log channel, where one can be found, so that it is seen by whoever + watches that channel rather than only by whoever can read the console. + """ + settings_validation_error: SettingsValidationError + try: + reload_settings() + except SettingsValidationError as settings_validation_error: + UNVALIDATED_WEBHOOK_URL: Final[str | None] = _webhook_url_written_within_file() + if UNVALIDATED_WEBHOOK_URL is not None: + relay_start_up_error_to_discord_log_channel( + settings_validation_error, UNVALIDATED_WEBHOOK_URL + ) + raise + + messages_error: ImproperlyConfiguredError + try: + messages.reload() + except ImproperlyConfiguredError as messages_error: + if settings.logging.discord_channel is not None: + relay_start_up_error_to_discord_log_channel( + messages_error, str(settings.logging.discord_channel.webhook_url) + ) + raise + + logger.debug("Begin database setup") + + importlib.import_module("db") + importlib.import_module("django.core.management").call_command("migrate") + + logger.debug("Database setup completed") diff --git a/config/_accessor.py b/config/_accessor.py new file mode 100644 index 000000000..381d268a7 --- /dev/null +++ b/config/_accessor.py @@ -0,0 +1,376 @@ +""" +Runtime access to the validated deployment configuration. + +Holds the currently-loaded configuration as a single immutable snapshot, replaced +wholesale whenever the configuration is reloaded. Because a reload swaps one reference +rather than mutating settings individually, no reader can ever observe a partially +applied configuration, even if reloading fails partway through. + +A setting that requires a restart keeps the value TeX-Bot started with, however many +times the configuration is reloaded. The value written within the file is held alongside +it, & takes effect once TeX-Bot is restarted. +""" + +from typing import TYPE_CHECKING, override + +from pydantic import BaseModel, ValidationError + +from exceptions import ( + InvalidSettingsFileError, + SettingsFileNotFoundError, + SettingsNotLoadedError, + SettingsValidationError, +) + +from ._document import SettingsDocument +from ._schema import ( + SettingsSchema, + get_settings_metadata, + nested_settings_model_of, + setting_names_within, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from collections.abc import Set as AbstractSet + from pathlib import Path + from typing import Final + + from pydantic.fields import FieldInfo + + from ._schema import ( + CommandsSettings, + CommunityGroupSettings, + DiscordSettings, + LoggingSettings, + RemindersSettings, + ) + + +__all__: Sequence[str] = ("SettingsAccessor",) + + +class _LoadedSettings: + """ + A validated configuration snapshot, paired with the document it was parsed from. + + Holding both within a single immutable object allows a reload to replace them together, + by rebinding one reference, so the two can never disagree with one another. + """ + + @override + def __init__( + self, + snapshot: SettingsSchema, + document: SettingsDocument, + running_snapshot: SettingsSchema, + ) -> None: + """Initialise a snapshot paired with the document it was parsed from.""" + self._snapshot: SettingsSchema = snapshot + self._document: SettingsDocument = document + self._running_snapshot: SettingsSchema = running_snapshot + + @property + def snapshot(self) -> SettingsSchema: + """The validated settings parsed from the document.""" + return self._snapshot + + @property + def document(self) -> SettingsDocument: + """The parsed document that the snapshot was loaded from.""" + return self._document + + @property + def running_snapshot(self) -> SettingsSchema: + """ + The settings TeX-Bot is running with. + + The same as the snapshot parsed from the document, except that every setting + requiring a restart holds the value TeX-Bot started with. + """ + return self._running_snapshot + + +_MISSING: Final[object] = object() + + +def flatten_settings(model: BaseModel, prefix: str = "") -> Mapping[str, object]: + """ + Flatten a settings model into a mapping of colon-separated key paths to values. + + Nested sections are expanded recursively, so that + `{"discord": {"bot-token": ...}}` becomes `{"discord:bot-token": ...}`, + matching the key paths used by the `/config` command. + """ + flattened_settings: dict[str, object] = {} + + field_name: str + field: FieldInfo + for field_name, field in type(model).model_fields.items(): + value: object = getattr(model, field_name) + KEY_PATH: str = f"{prefix}{field_name.replace('_', '-')}" + + if isinstance(value, BaseModel): + flattened_settings.update(flatten_settings(value, prefix=f"{KEY_PATH}:")) + continue + + NESTED_MODEL: type[BaseModel] | None = nested_settings_model_of(field) + if NESTED_MODEL is not None: + # NOTE: An optional section left out of the file holds no value of its own; + # every setting within it is simply unset. Naming those settings, rather than + # the section holding them, keeps every key path reported by a reload one that + # the `/config` command recognises. + flattened_settings.update( + dict.fromkeys(setting_names_within(NESTED_MODEL, prefix=f"{KEY_PATH}:")) + ) + continue + + flattened_settings[KEY_PATH] = value + + return flattened_settings + + +def _setting_section(model: BaseModel, field_name: str) -> BaseModel: + SECTION: Final[object] = getattr(model, field_name) + + if not isinstance(SECTION, BaseModel): + NOT_A_SECTION_MESSAGE: Final[str] = ( + f"{field_name!r} does not hold a section of settings, " + "so a setting cannot be found within it." + ) + raise TypeError(NOT_A_SECTION_MESSAGE) + + return SECTION + + +def _setting_value(model: BaseModel, field_names: Sequence[str]) -> object: + if len(field_names) == 1: + return getattr(model, field_names[0]) + + return _setting_value(_setting_section(model, field_names[0]), field_names[1:]) + + +def _with_setting_value[T: BaseModel]( + model: T, field_names: Sequence[str], value: object +) -> T: + """Return a copy of the given settings model, with a single setting replaced.""" + if len(field_names) == 1: + return model.model_copy(update={field_names[0]: value}) + + return model.model_copy( + update={ + field_names[0]: _with_setting_value( + _setting_section(model, field_names[0]), field_names[1:], value + ) + } + ) + + +def _restart_setting_key_paths() -> AbstractSet[str]: + """Return the key path of every setting that requires a restart to take effect.""" + return { + key_path + for key_path, setting_metadata in get_settings_metadata().items() + if setting_metadata.requires_restart + } + + +def _with_start_up_values_of_restart_settings( + snapshot: SettingsSchema, start_up_snapshot: SettingsSchema +) -> SettingsSchema: + """ + Return a copy of the given snapshot, holding the start-up value of every restart setting. + + A setting requiring a restart is one that TeX-Bot reads only as it starts up, so + letting a reload replace it would leave the parts of TeX-Bot that read it once out + of step with those that read it on every use. + """ + running_snapshot: SettingsSchema = snapshot + + key_path: str + for key_path in _restart_setting_key_paths(): + FIELD_NAMES: Sequence[str] = tuple( + key_part.replace("-", "_") for key_part in key_path.split(":") + ) + running_snapshot = _with_setting_value( + running_snapshot, FIELD_NAMES, _setting_value(start_up_snapshot, FIELD_NAMES) + ) + + return running_snapshot + + +class SettingsAccessor: + """ + Provides access to the validated configuration settings. + + Settings are accessed by section, as attributes + (for example: `settings.discord.bot_token`). + """ + + @override + def __init__(self) -> None: + """Initialise an accessor holding no configuration until it is first loaded.""" + self._loaded: _LoadedSettings | None = None + self._start_up_snapshot: SettingsSchema | None = None + + @property + def is_loaded(self) -> bool: + """Whether any configuration has been loaded yet.""" + return self._loaded is not None + + @property + def _current(self) -> _LoadedSettings: + """The currently-loaded configuration, raising if none has been loaded yet.""" + if self._loaded is None: + raise SettingsNotLoadedError + + return self._loaded + + @property + def file_path(self) -> Path: + """The location of the configuration file that is currently loaded.""" + return self._current.document.file_path + + @property + def document(self) -> SettingsDocument: + """ + The document that the currently-loaded configuration was parsed from. + + Used to rewrite individual settings while keeping the order & quoting of the file + that a human wrote. + """ + return self._current.document + + def file_has_changed(self) -> bool: + """ + Whether the configuration file differs from the configuration loaded from it. + + Compared as the documents parse to, rather than as raw text, so that a file + rewritten with different line endings is not mistaken for one that was edited. + Comments are not compared, because TeX-Bot does not write them back. + + A file that can no longer be read at all is reported as changed, rather than + raising: it certainly no longer holds the configuration that was loaded from it, + & saying so is what allows the caller to explain that instead of failing. + """ + if self._loaded is None: + return False + + try: + return SettingsDocument.load(self.file_path).dump() != self._loaded.document.dump() + except SettingsFileNotFoundError, InvalidSettingsFileError, OSError: + return True + + def reload(self, file_path: Path | None = None) -> AbstractSet[str]: + """ + Load the configuration file, replacing any previously loaded configuration. + + Returns the set of settings key paths whose values differ from those previously + loaded. Every setting is reported as changed upon the very first load. + + The previously loaded configuration is left untouched if the file cannot be read + or contains invalid settings, so that a bad edit cannot take a running bot down. + + The very first configuration loaded is the one TeX-Bot starts with, so every + setting requiring a restart keeps its value from that load until TeX-Bot restarts. + """ + document: SettingsDocument = SettingsDocument.load(file_path) + + validation_error: ValidationError + try: + snapshot: SettingsSchema = SettingsSchema.model_validate(document.raw) + except ValidationError as validation_error: + raise SettingsValidationError( + document.format_validation_error(validation_error) + ) from validation_error + + PREVIOUS_SETTINGS: Final[Mapping[str, object]] = ( + {} if self._loaded is None else flatten_settings(self._loaded.snapshot) + ) + NEW_SETTINGS: Final[Mapping[str, object]] = flatten_settings(snapshot) + + if self._start_up_snapshot is None: + self._start_up_snapshot = snapshot + + # NOTE: Rebinding this single reference is what makes a reload atomic: every + # reader either sees the whole of the previous configuration, or the whole of the + # new one. Both the validation above & the file reading before it can raise, and + # neither will have left the currently-loaded configuration partially updated. + self._loaded = _LoadedSettings( + snapshot=snapshot, + document=document, + running_snapshot=_with_start_up_values_of_restart_settings( + snapshot, self._start_up_snapshot + ), + ) + + return { + key_path + for key_path in (PREVIOUS_SETTINGS.keys() | NEW_SETTINGS.keys()) + if PREVIOUS_SETTINGS.get(key_path, _MISSING) + != NEW_SETTINGS.get(key_path, _MISSING) + } + + def as_flat_mapping(self) -> Mapping[str, object]: + """ + Return every running setting, as a mapping of colon-separated key paths to values. + + Used by the `/config` command to view settings by name. A setting requiring a + restart is given the value TeX-Bot started with, which is the one in use. + """ + return flatten_settings(self._current.running_snapshot) + + def as_flat_file_mapping(self) -> Mapping[str, object]: + """ + Return every loaded setting, with the values held by the file when last loaded. + + Unlike `as_flat_mapping()`, this includes the new value of any setting that will + not take effect until TeX-Bot is restarted. + """ + return flatten_settings(self._current.snapshot) + + @property + def values_awaiting_restart(self) -> Mapping[str, object]: + """ + Every setting whose loaded value will not take effect until TeX-Bot is restarted. + + Each is mapped to the value held by the file, which differs from the value that + TeX-Bot is running with. + """ + RUNNING_SETTINGS: Final[Mapping[str, object]] = self.as_flat_mapping() + + return { + key_path: file_value + for key_path, file_value in self.as_flat_file_mapping().items() + if file_value != RUNNING_SETTINGS.get(key_path, _MISSING) + } + + @property + def logging(self) -> LoggingSettings: + """Settings controlling every logging destination TeX-Bot can write to.""" + return self._current.running_snapshot.logging + + @property + def discord(self) -> DiscordSettings: + """Settings describing how TeX-Bot connects to Discord.""" + return self._current.running_snapshot.discord + + @property + def community_group(self) -> CommunityGroupSettings: + """Settings describing the community group that TeX-Bot is deployed for.""" + return self._current.running_snapshot.community_group + + @property + def commands(self) -> CommandsSettings: + """Settings controlling the behaviour of TeX-Bot's individual commands.""" + return self._current.running_snapshot.commands + + @property + def reminders(self) -> RemindersSettings: + """Settings controlling every kind of reminder that TeX-Bot can send.""" + return self._current.running_snapshot.reminders + + @property + def auto_add_committee_to_threads(self) -> bool: + """Whether committee members are automatically added to newly created threads.""" + return self._current.running_snapshot.auto_add_committee_to_threads diff --git a/config/_document.py b/config/_document.py new file mode 100644 index 000000000..bf889ac2f --- /dev/null +++ b/config/_document.py @@ -0,0 +1,489 @@ +""" +Reading, writing & error-reporting for the raw deployment configuration file. + +This module owns every interaction with `tex-bot-deployment.yaml` as a *document*: +locating it, parsing it while recording the line each setting is written upon, writing it +back atomically, and mapping validation failures onto the lines that caused them. + +Comments within the file are read, but are not written back: a comment cannot be kept +beside the setting it describes once settings around it are added or removed. + +It deliberately knows nothing about what any individual setting means; +the shape & meaning of the configuration is declared solely within `config._schema`. +""" + +import io +import logging +import os +import stat +from pathlib import Path +from typing import TYPE_CHECKING, override + +from ruamel.yaml import YAML +from ruamel.yaml.comments import CommentedMap +from ruamel.yaml.error import YAMLError + +from exceptions import InvalidSettingsFileError, SettingsFileNotFoundError + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from logging import Logger + from typing import Final, Self + + from pydantic import ValidationError + + +__all__: Sequence[str] = ( + "SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME", + "SettingsDocument", + "get_settings_file_path", +) + + +logger: Final[Logger] = logging.getLogger("TeX-Bot") + +PROJECT_ROOT: Final[Path] = Path(__file__).parent.parent.resolve() + +DEFAULT_SETTINGS_FILE_NAME: Final[str] = "tex-bot-deployment.yaml" + +SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME: Final[str] = "TEX_BOT_CONFIG_PATH" + + +def get_settings_file_path() -> Path: + """ + Locate the deployment configuration file. + + The location is taken from the `TEX_BOT_CONFIG_PATH` environment variable if it is set, + otherwise `tex-bot-deployment.yaml` alongside the project root is used. + """ + RAW_SETTINGS_FILE_PATH: Final[str | None] = os.getenv( + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME + ) + + if RAW_SETTINGS_FILE_PATH: + settings_file_path: Path = Path(RAW_SETTINGS_FILE_PATH).expanduser() + if not settings_file_path.is_file(): + SETTINGS_FILE_FROM_ENVIRONMENT_NOT_FOUND_MESSAGE: str = ( + f"The path given by the " + f"{SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME} environment variable " + f"does not refer to an existing file: {str(settings_file_path)!r}." + ) + raise SettingsFileNotFoundError(SETTINGS_FILE_FROM_ENVIRONMENT_NOT_FOUND_MESSAGE) + + return settings_file_path.resolve() + + default_settings_file_path: Path = PROJECT_ROOT / DEFAULT_SETTINGS_FILE_NAME + if not default_settings_file_path.is_file(): + NO_SETTINGS_FILE_MESSAGE: str = ( + f"No configuration file was found. Create a {DEFAULT_SETTINGS_FILE_NAME!r} file " + f"within {str(PROJECT_ROOT)!r}, or set the " + f"{SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME} environment variable " + f"to the location of your configuration file." + ) + raise SettingsFileNotFoundError(NO_SETTINGS_FILE_MESSAGE) + + return default_settings_file_path.resolve() + + +def _create_yaml_parser() -> YAML: + """Create a YAML parser that records where each value is written & how it is quoted.""" + yaml_parser: YAML = YAML() # NOTE: Defaults to round-trip mode + yaml_parser.preserve_quotes = True + # NOTE: Without a generous line width, writing a document back would re-wrap any long + # values it contains, producing spurious changes within otherwise untouched sections. + yaml_parser.width = 4096 + + return yaml_parser + + +def _without_comments(node: object) -> object: + """Return a copy of the given parsed YAML node, holding its values but no comments.""" + if isinstance(node, dict): + return {key: _without_comments(value) for key, value in node.items()} + + if isinstance(node, list): + return [_without_comments(value) for value in node] + + return node + + +class SettingsDocument: + """ + A single deployment configuration file, held as a parsed document. + + Holding the parsed document (rather than only the values taken from it) allows + individual settings to be rewritten while keeping the order & quoting of the file + that a human wrote, and allows an error to name the line that caused it. + """ + + @override + def __init__(self, file_path: Path, raw: CommentedMap) -> None: + """Initialise a configuration document already parsed from the given file path.""" + self._file_path: Path = file_path + self._raw: CommentedMap = raw + + @classmethod + def load(cls, file_path: Path | None = None) -> Self: + """Locate & parse the deployment configuration file.""" + RESOLVED_FILE_PATH: Final[Path] = ( + get_settings_file_path() if file_path is None else file_path + ) + + # NOTE: `get_settings_file_path()` has already checked that the file it returns + # exists, but an explicitly given path has not been checked by anything. Checking + # here keeps every failure to read the configuration reportable as one error type. + if not RESOLVED_FILE_PATH.is_file(): + EXPLICIT_SETTINGS_FILE_NOT_FOUND_MESSAGE: str = ( + f"No configuration file exists at {str(RESOLVED_FILE_PATH)!r}." + ) + raise SettingsFileNotFoundError(EXPLICIT_SETTINGS_FILE_NOT_FOUND_MESSAGE) + + unicode_decode_error: UnicodeDecodeError + try: + raw_file_contents: str = RESOLVED_FILE_PATH.read_text(encoding="utf-8") + except UnicodeDecodeError as unicode_decode_error: + NOT_UTF_8_MESSAGE: Final[str] = ( + f"{RESOLVED_FILE_PATH.name} must be saved as UTF-8 text, " + f"but could not be read as UTF-8: {unicode_decode_error}" + ) + raise InvalidSettingsFileError(NOT_UTF_8_MESSAGE) from unicode_decode_error + + yaml_parse_error: YAMLError + try: + # NOTE: Annotated as `object` because an arbitrary YAML file need not contain a + # mapping at its top level: an empty file parses to `None`, and a file holding + # only a scalar or a sequence parses to that value. + raw: object = _create_yaml_parser().load(raw_file_contents) + except YAMLError as yaml_parse_error: + INVALID_YAML_MESSAGE: str = ( + f"{RESOLVED_FILE_PATH.name} is not a valid YAML file: {yaml_parse_error}" + ) + raise InvalidSettingsFileError(INVALID_YAML_MESSAGE) from yaml_parse_error + + if raw is None: + EMPTY_SETTINGS_FILE_MESSAGE: str = f"{RESOLVED_FILE_PATH.name} is empty." + raise InvalidSettingsFileError(EMPTY_SETTINGS_FILE_MESSAGE) + + # NOTE: Checking for `CommentedMap` (rather than merely `dict`) also guarantees the + # presence of the `lc` line-comment data that `line_number_of()` relies upon. + if not isinstance(raw, CommentedMap): + NOT_A_MAPPING_MESSAGE: str = ( + f"{RESOLVED_FILE_PATH.name} must contain a mapping of configuration " + f"settings at its top level, but contains " + f"{type(raw).__name__} instead." + ) + raise InvalidSettingsFileError(NOT_A_MAPPING_MESSAGE) + + return cls(file_path=RESOLVED_FILE_PATH, raw=raw) + + @property + def file_path(self) -> Path: + """The location of the file this document was parsed from.""" + return self._file_path + + @property + def raw(self) -> CommentedMap: + """ + The parsed document, retaining the order & quoting of the original file. + + Mutating this mapping does not write anything to disk; + `write()` must be called to persist any changes made. + """ + return self._raw + + def contains(self, key_path: Sequence[str]) -> bool: + """Whether the given sequence of keys is written within this document.""" + node: object = self._raw + + key: str + for key in key_path: + if not isinstance(node, dict) or key not in node: + return False + + node = node[key] + + return True + + def set_value(self, key_path: Sequence[str], value: object) -> None: + """ + Write the given value at the given sequence of keys, creating any absent sections. + + Nothing is written to disk until `write()` is called. + """ + if not key_path: + EMPTY_KEY_PATH_MESSAGE: str = "A setting to change must be named." + raise ValueError(EMPTY_KEY_PATH_MESSAGE) + + node: CommentedMap = self._raw + + key: str + for key in key_path[:-1]: + # NOTE: A section written with nothing beneath it (because every setting within + # it has been commented out, for example) holds null, & is just as absent. + if node.get(key) is None: + node[key] = CommentedMap() + + child_node: object = node[key] + if not isinstance(child_node, CommentedMap): + NOT_A_SECTION_MESSAGE: str = ( + f"{self._file_path.name} cannot hold the setting " + f"{':'.join(key_path)!r}, because {key!r} is not a section." + ) + raise InvalidSettingsFileError(NOT_A_SECTION_MESSAGE) + + node = child_node + + node[key_path[-1]] = value + + def unset_value(self, key_path: Sequence[str]) -> bool: + """ + Remove the given sequence of keys, reporting whether it was written at all. + + Any section left empty is kept, rather than being removed alongside the setting, + because a section may be required to be present even when it holds nothing. + + Nothing is written to disk until `write()` is called. + """ + if not self.contains(key_path): + return False + + node: object = self._raw + + key: str + for key in key_path[:-1]: + if TYPE_CHECKING: + assert isinstance(node, dict) + + node = node[key] + + if TYPE_CHECKING: + assert isinstance(node, dict) + + del node[key_path[-1]] + + return True + + def dump(self) -> str: + """ + Serialise this document back into YAML, without any of its comments. + + A comment is attached to whichever setting happens to precede it, so once a + setting is added or removed, keeping it would leave it describing the wrong + setting, or written out at an indentation that is no longer valid YAML. + """ + output_buffer: io.StringIO = io.StringIO() + _create_yaml_parser().dump(_without_comments(self._raw), output_buffer) + + return output_buffer.getvalue() + + def _permissions_of_existing_file(self) -> int | None: + """Return the permission bits of this document's file, if it can be determined.""" + stat_error: OSError + try: + return stat.S_IMODE(self._file_path.stat().st_mode) + except OSError as stat_error: + logger.debug( + "Could not read the permissions of %s (%s); " + "the file will be written with the permissions a new file is given.", + self._file_path, + stat_error.strerror or stat_error, + ) + return None + + @classmethod + def _write_privately(cls, file_path: Path, contents: str) -> None: + """ + Write the given contents into the given path, readable only by its owner. + + The configuration file holds the bot token & the MSL authentication cookie, so + it must never exist (even momentarily, as the temporary file written below does) + with the permissions a newly created file would otherwise be given. + """ + file_descriptor: int = os.open(file_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + + opened_file: io.TextIOWrapper + with os.fdopen(file_descriptor, "w", encoding="utf-8") as opened_file: + opened_file.write(contents) + + def write(self) -> None: + """ + Persist this document to disk, atomically where the filesystem allows it. + + The serialised document is written to a temporary file alongside the destination + and then moved into place, so that a failure partway through writing cannot leave + a truncated configuration file behind. + + Where that move is rejected, the document is written directly instead. This + happens when the configuration file is an individually mounted file within a + container, because a rename cannot replace a mount point. Writing directly is not + atomic, but it is the only option available in that case; mounting the directory + holding the configuration file, rather than the file itself, avoids it entirely. + + The permissions of the file being replaced are carried across onto the file + replacing it, so that a deployment which has deliberately restricted who may read + its configuration file does not silently have those restrictions lifted. + + Nothing is written if the serialised document would not read back as the same + settings, so that a change can never leave behind a file TeX-Bot cannot load. + """ + NEW_FILE_CONTENTS: Final[str] = self.dump() + + self._ensure_reads_back_unchanged(NEW_FILE_CONTENTS) + + EXISTING_FILE_PERMISSIONS: Final[int | None] = self._permissions_of_existing_file() + + temporary_file_path: Path = self._file_path.with_name( + f"{self._file_path.name}.{os.getpid()}.tmp" + ) + + try: + self._write_privately(temporary_file_path, NEW_FILE_CONTENTS) + + if EXISTING_FILE_PERMISSIONS is not None: + temporary_file_path.chmod(EXISTING_FILE_PERMISSIONS) + + replace_error: OSError + try: + # NOTE: `os.replace()` is atomic where the source & destination are located + # upon the same filesystem, which writing the temporary file alongside the + # destination guarantees. + os.replace(temporary_file_path, self._file_path) # noqa: PTH105 + except OSError as replace_error: + logger.debug( + ( + "Could not atomically replace %s (%s); " + "falling back to writing it in place." + ), + self._file_path, + replace_error.strerror or replace_error, + ) + self._file_path.write_text(NEW_FILE_CONTENTS, encoding="utf-8") + finally: + temporary_file_path.unlink(missing_ok=True) + + def _ensure_reads_back_unchanged(self, new_file_contents: str) -> None: + """ + Refuse to write contents that would not read back as this document's settings. + + Checked after every serialisation, so that a fault in writing a document back + can never leave behind a file that TeX-Bot cannot start from. + """ + UNSAFE_TO_WRITE_MESSAGE: Final[str] = ( + f"{self._file_path.name} was not changed, because the rewritten file would not " + "read back as the settings it should hold. " + "Make this change by editing the file by hand instead." + ) + + yaml_parse_error: YAMLError + try: + READ_BACK_CONTENTS: Final[object] = _create_yaml_parser().load(new_file_contents) + except YAMLError as yaml_parse_error: + raise InvalidSettingsFileError(UNSAFE_TO_WRITE_MESSAGE) from yaml_parse_error + + if self._raw != READ_BACK_CONTENTS: + raise InvalidSettingsFileError(UNSAFE_TO_WRITE_MESSAGE) + + def line_number_of(self, key_path: Sequence[str | int]) -> int | None: + """ + Return the line within the original file that the given sequence of keys refers to. + + Where the given keys cannot be fully resolved (because a required key is absent + from the file, for example), the line of the deepest key that *could* be resolved + is returned, so that an error can still be pointed at the relevant section. + """ + node: object = self._raw + deepest_known_line_number: int | None = None + + key: str | int + for key in key_path: + RESOLVED_KEY: tuple[int, object] | None = self._resolved_key(node, key) + if RESOLVED_KEY is None: + break + + deepest_known_line_number, node = RESOLVED_KEY + + return deepest_known_line_number + + @classmethod + def _resolved_key(cls, node: object, key: str | int) -> tuple[int, object] | None: + """ + Resolve one key of a key path, returning its line paired with the value held at it. + + Both mappings & sequences are resolved, because a validation failure reported + against a single entry of a sequence (one role within `displayed-roles`, for + example) names that entry by its index, & so should be pointed at the line + holding it rather than at the line the sequence itself begins upon. + + `None` is returned where the node does not hold the given key at all, and also + for a key that was added to the document rather than parsed from the file, + because such a key has no line within the file to report. The latter happens + whenever the `/config` command writes a setting for the first time. + """ + # NOTE: A node parsed by the round-trip parser carries the `lc` line-comment data + # that the positions below are read from; one added to the document does not. + if getattr(node, "lc", None) is None: + return None + + key_position: object + child_node: object + + if isinstance(node, dict): + if key not in node: + return None + + try: + key_position = node.lc.key(key) # type: ignore[attr-defined] + except KeyError: + return None + + child_node = node[key] + + elif isinstance(node, list) and isinstance(key, int) and 0 <= key < len(node): + try: + key_position = node.lc.item(key) # type: ignore[attr-defined] + except KeyError, IndexError: + return None + + child_node = node[key] + + else: + return None + + if not isinstance(key_position, tuple): + return None + + # NOTE: `lc` reports a zero-indexed line, whereas humans (& every editor) + # count the first line of a file as line 1. + return (int(key_position[0]) + 1, child_node) + + def _format_single_error(self, key_path: Sequence[str | int], message: str) -> str: + """Format a single validation failure, prefixed with the location that caused it.""" + LINE_NUMBER: Final[int | None] = self.line_number_of(key_path) + + LOCATION: Final[str] = ( + f"{self._file_path.name}:{LINE_NUMBER}" + if LINE_NUMBER is not None + else self._file_path.name + ) + SETTING_NAME: Final[str] = ( + ":".join(str(key) for key in key_path) if key_path else "(whole file)" + ) + + return f"{LOCATION} {SETTING_NAME}\n {message}" + + def format_validation_error(self, validation_error: ValidationError) -> str: + """ + Render a validation failure into a message suitable for a human to act upon. + + Every reported failure is annotated with the line of the configuration file that + caused it. The offending values themselves are deliberately excluded, so that + secrets cannot leak into logs or into any message sent to a Discord channel. + """ + formatted_errors: Iterator[str] = ( + self._format_single_error( + key_path=single_error["loc"], message=single_error["msg"] + ) + for single_error in validation_error.errors(include_input=False, include_url=False) + ) + + return "\n".join(formatted_errors) diff --git a/config/_editor.py b/config/_editor.py new file mode 100644 index 000000000..c39f3e6ed --- /dev/null +++ b/config/_editor.py @@ -0,0 +1,341 @@ +""" +Changing individual settings within the deployment configuration file. + +Every change is applied to the configuration file read afresh, & validated in full, +before anything is written, so that a mistaken value can never leave TeX-Bot holding a +configuration file it would refuse to load. A file that has been changed by hand since +it was last loaded is refused outright, rather than merged into, so that every change +is made against the configuration that TeX-Bot is actually running. + +This module holds no knowledge of Discord: it turns the text a committee member typed +into a value, decides whether that value is acceptable, & renders values back into +something readable. Doing so here (rather than within the `/config` command itself) +keeps all of it testable without a connection to Discord. +""" + +import datetime +from typing import TYPE_CHECKING + +from pydantic import SecretStr, ValidationError +from ruamel.yaml import YAML +from ruamel.yaml.error import YAMLError + +from exceptions import ( + InvalidSettingsFileError, + SettingsFileChangedError, + SettingsFileNotFoundError, + SettingsValidationError, + UnknownSettingError, +) + +from ._accessor import flatten_settings +from ._document import SettingsDocument +from ._schema import SettingsSchema, get_settings_metadata + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from pathlib import Path + from typing import Final + + from ._schema import ConfigSettingMetadata + + +__all__: Sequence[str] = ( + "SETTING_NAME_SEPARATOR", + "documented_setting_names", + "format_file_difference", + "format_setting_value", + "parse_setting_value", + "setting_metadata", + "validated_document_with_setting_removed", + "validated_document_with_setting_set", +) + + +SETTING_NAME_SEPARATOR: Final[str] = ":" + +REDACTED_VALUE_DISPLAY: Final[str] = "\\*\\*\\*\\*\\*\\* _(hidden)_" + +UNSET_VALUE_DISPLAY: Final[str] = "_(not set)_" + +# NOTE: The ways of writing "nothing" that YAML recognises, so that a setting cleared by +# one of them is cleared rather than being set to the word itself. +_NULL_LITERALS: Final[frozenset[str]] = frozenset({"null", "~"}) + + +def documented_setting_names() -> Sequence[str]: + """Return the name of every setting that can be viewed or changed, in order.""" + return sorted(get_settings_metadata()) + + +def _key_path_of(setting_name: str) -> Sequence[str]: + """Convert a colon-separated setting name into the sequence of keys it refers to.""" + if setting_name not in get_settings_metadata(): + raise UnknownSettingError(setting_name) + + return setting_name.split(SETTING_NAME_SEPARATOR) + + +def _read_as_yaml(raw_value: str) -> object: + """Read the given text as though it had been written into the configuration file.""" + try: + # NOTE: Deliberately the safe parser: the value comes from whoever ran the + # command, & the round-trip parser used elsewhere can construct arbitrary + # Python objects from a value that names them. + return YAML(typ="safe", pure=True).load(raw_value) + except YAMLError: + return None + + +def parse_setting_value(setting_name: str, raw_value: str) -> object: + """ + Convert the text a committee member typed into the value to write into the file. + + The text is read exactly as it would be if it had been written into the + configuration file by hand, so that `true` becomes a boolean, `30` becomes a number, + and `1h30m` remains the text of a duration. + + A setting declared to hold text is kept as text, so that a value which merely looks + like a number (an organisation ID of `1234`, for example) is not written as one & + then rejected for being the wrong type. Quoting such a value is still respected, + so that `"1234"` means the same as `1234` rather than including the quotes. + + Writing `null` (or `~`) clears a setting whatever type it holds, including one that + holds text. `/config unset` removes such a setting from the file altogether, whereas + this leaves it written there, holding nothing. + """ + PARSED_VALUE: Final[object] = _read_as_yaml(raw_value) + + if raw_value.strip().lower() in _NULL_LITERALS: + # NOTE: Clearing a setting is meant the same way whatever type that setting holds, + # so one declared to hold text is no exception: keeping `null` as the text it + # looks like would set that setting to the word itself rather than to nothing. + return None + + if setting_metadata(setting_name).holds_text: + return PARSED_VALUE if isinstance(PARSED_VALUE, str) else raw_value + + if isinstance(PARSED_VALUE, dict): + # NOTE: A value holding a colon parses as a mapping, even though somebody typing + # `Computer Science: Society` into a single setting meant it as plain text. + return raw_value + + if PARSED_VALUE is None: + # NOTE: A value beginning with `#` parses as a comment, & so as nothing at all, + # as does a value that cannot be read as YAML at all. + return raw_value + + return PARSED_VALUE + + +def _format_duration(duration: datetime.timedelta) -> str: + """Render a length of time in the same format the configuration file holds it in.""" + remaining_seconds: float = duration.total_seconds() + if remaining_seconds <= 0: + return "0s" + + formatted_duration: str = "" + + unit_name: str + seconds_within_unit: int + for unit_name, seconds_within_unit in (("d", 86400), ("h", 3600), ("m", 60)): + unit_count: int = int(remaining_seconds // seconds_within_unit) + if unit_count: + formatted_duration += f"{unit_count}{unit_name}" + remaining_seconds -= unit_count * seconds_within_unit + + if remaining_seconds: + formatted_duration += f"{remaining_seconds:g}s" + + return formatted_duration + + +def format_setting_value(value: object, *, secret: bool) -> str: + """ + Render the value of a single setting into something readable. + + A secret value is never rendered, so that displaying a setting cannot reveal a + credential to whoever can see the response. + """ + if value is None: + return UNSET_VALUE_DISPLAY + + if secret or isinstance(value, SecretStr): + return REDACTED_VALUE_DISPLAY + + if isinstance(value, datetime.timedelta): + return f"`{_format_duration(value)}`" + + if isinstance(value, tuple): + return ", ".join(f"`{single_value}`" for single_value in value) or UNSET_VALUE_DISPLAY + + if isinstance(value, bool): + return f"`{str(value).lower()}`" + + return f"`{value}`" + + +def _snapshot_of(document: SettingsDocument) -> SettingsSchema: + """Return the settings held by the given document, refusing it if they are invalid.""" + validation_error: ValidationError + try: + return SettingsSchema.model_validate(document.raw) + except ValidationError as validation_error: + raise SettingsValidationError( + document.format_validation_error(validation_error) + ) from validation_error + + +def _validated(document: SettingsDocument) -> SettingsDocument: + """Return the given document, having checked that it holds a valid configuration.""" + _snapshot_of(document) + + return document + + +def format_file_difference( + setting_name: str, + loaded_value: object, + *, + secret: bool, + file_path: Path | None = None, +) -> str: + """ + Describe how the configuration file's value for a setting differs from the loaded one. + + Intended to be shown alongside the value TeX-Bot is running, once the file is known + to have been edited since it was last loaded, so that whoever is looking at a setting + can see what reloading would change it to rather than only being told to reload. + + The value compared against is the one last loaded from the file. That is the running + value, except for a setting whose new value is waiting for TeX-Bot to restart. + + The file compared against is the one the running configuration was loaded from, which + must be given explicitly: it is not necessarily the one that would be located afresh. + """ + file_error: Exception + try: + FILE_VALUES: Final[Mapping[str, object]] = flatten_settings( + _snapshot_of(SettingsDocument.load(file_path)) + ) + except ( + SettingsValidationError, + SettingsFileNotFoundError, + InvalidSettingsFileError, + OSError, + ) as file_error: + return ( + "\n\n:warning: The configuration file has been edited since TeX-Bot last " + "loaded it, but cannot be loaded as it currently stands:\n" + f"```\n{file_error}\n```" + ) + + # NOTE: A setting within a section that has been left out of the file entirely has no + # entry of its own, & is simply unset. + FILE_VALUE: Final[object] = FILE_VALUES.get(setting_name) + + if loaded_value == FILE_VALUE: + return ( + "\n\n:information_source: The configuration file has been edited since " + "TeX-Bot last loaded it, though not this setting. " + "Run `/config reload` to apply those edits." + ) + + if secret: + return ( + "\n\n:warning: The configuration file holds a different value for this " + "setting, which TeX-Bot has not loaded. " + "Run `/config reload` to apply that edit." + ) + + return ( + f"\n\n:warning: The configuration file has been edited since TeX-Bot last " + f"loaded it:\n" + f"- last loaded: {format_setting_value(loaded_value, secret=secret)}\n" + f"- within the file: {format_setting_value(FILE_VALUE, secret=secret)}\n" + f"Run `/config reload` to apply that edit." + ) + + +def _read_unchanged_file(loaded_document: SettingsDocument | None) -> SettingsDocument: + """ + Read the configuration file again, refusing it if it no longer matches what is loaded. + + A change made by hand is refused rather than merged into, so that changing one + setting cannot silently apply somebody else's unrelated edits alongside it, nor + report that TeX-Bot must be restarted for a setting its author never touched. + + The file read is the one the given document was loaded from, so that a change is + always made to the file TeX-Bot is running, rather than to whichever file would be + located afresh. + """ + document: SettingsDocument = SettingsDocument.load( + None if loaded_document is None else loaded_document.file_path + ) + + # NOTE: Nothing has been loaded for the file to have diverged from while TeX-Bot is + # still starting up, so there is nothing to compare it against. + if loaded_document is not None and document.dump() != loaded_document.dump(): + raise SettingsFileChangedError + + return document + + +def validated_document_with_setting_set( + setting_name: str, value: object, loaded_document: SettingsDocument | None = None +) -> SettingsDocument: + """ + Return the configuration file, holding the given value for the given setting. + + The file is refused if it has been changed by hand since it was last loaded, so that + a change is only ever applied to the configuration TeX-Bot is actually running. + + Nothing is written to disk: the returned document must be written by its caller. + """ + KEY_PATH: Final[Sequence[str]] = _key_path_of(setting_name) + + document: SettingsDocument = _read_unchanged_file(loaded_document) + document.set_value(KEY_PATH, value) + + return _validated(document) + + +def validated_document_with_setting_removed( + setting_name: str, loaded_document: SettingsDocument | None = None +) -> SettingsDocument | None: + """ + Return the configuration file, no longer holding the given setting. + + `None` is returned where the setting was not written within the file to begin with, + because removing it would leave the file exactly as it already is. + + The file is refused if it has been changed by hand since it was last loaded. + + A setting that an optional section cannot be used without is removed along with the + whole of that section, because the section would no longer be valid without it. + + Nothing is written to disk: the returned document must be written by its caller. + """ + KEY_PATH: Final[Sequence[str]] = _key_path_of(setting_name) + REQUIRED_BY_OPTIONAL_SECTION: Final[str | None] = setting_metadata( + setting_name + ).required_by_optional_section + + document: SettingsDocument = _read_unchanged_file(loaded_document) + if not document.unset_value(KEY_PATH): + return None + + if REQUIRED_BY_OPTIONAL_SECTION is not None: + document.unset_value(REQUIRED_BY_OPTIONAL_SECTION.split(SETTING_NAME_SEPARATOR)) + + return _validated(document) + + +def setting_metadata(setting_name: str) -> ConfigSettingMetadata: + """Return the metadata describing the given setting.""" + SETTINGS_METADATA: Final[Mapping[str, ConfigSettingMetadata]] = get_settings_metadata() + + if setting_name not in SETTINGS_METADATA: + raise UnknownSettingError(setting_name) + + return SETTINGS_METADATA[setting_name] diff --git a/config/_logging.py b/config/_logging.py new file mode 100644 index 000000000..64196ba32 --- /dev/null +++ b/config/_logging.py @@ -0,0 +1,248 @@ +""" +Application of the logging configuration held within the settings. + +Logging is set up from the loaded settings rather than read directly from the +environment, so that changing a log level within the configuration file takes effect +upon the next reload without restarting TeX-Bot. +""" + +import logging +from typing import TYPE_CHECKING, NamedTuple + +from discord_logging.handler import DiscordHandler + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from logging import Handler, Logger + from typing import Final + + from ._schema import ( + DiscordAPILoggingSettings, + DiscordChannelLoggingSettings, + LoggingSettings, + ) + + +__all__: Sequence[str] = ( + "DISCORD_LOGGER_NAME", + "LOGGER_NAME", + "apply_logging_settings", + "relay_start_up_error_to_discord_log_channel", + "set_discord_log_channel_identity", +) + + +# NOTE: These hold the *names* of the loggers to retrieve, rather than the loggers +# themselves, so `Final[str]` is the correct annotation despite what CAR201 infers +# from the variable names. +LOGGER_NAME: Final[str] = "TeX-Bot" # noqa: CAR201 + +DISCORD_LOGGER_NAME: Final[str] = "discord" # noqa: CAR201 + +DEFAULT_DISCORD_LOGGING_HANDLER_DISPLAY_NAME: Final[str] = "TeX-Bot" + +logger: Final[Logger] = logging.getLogger(LOGGER_NAME) + +discord_logger: Final[Logger] = logging.getLogger(DISCORD_LOGGER_NAME) + + +# NOTE: The name & avatar that logs are relayed into the Discord log channel under. +# TeX-Bot's own name & avatar are only known once it has logged in to Discord, so a +# placeholder is used until then. Held here, rather than only upon the handler, so +# that the handler created afresh by each reload is given them too. +class _DiscordLogChannelIdentity(NamedTuple): + """The name & avatar that logs are relayed into the Discord log channel under.""" + + display_name: str + avatar_url: str | None + + +_discord_log_channel_identity: _DiscordLogChannelIdentity = _DiscordLogChannelIdentity( + display_name=DEFAULT_DISCORD_LOGGING_HANDLER_DISPLAY_NAME, avatar_url=None +) + + +def _remove_handlers_of_type( + target_logger: Logger, handler_type: type, *, excluding: type | None = None +) -> None: + """ + Remove every handler of the given type from the given logger. + + A subtype of that type may be excluded, because the logging module's own handler + hierarchy does not match the destinations they write to: `FileHandler` subclasses + `StreamHandler`, so removing every stream handler would otherwise also remove the + file handler that a different destination's settings are responsible for. + """ + existing_handler: Handler + for existing_handler in tuple(target_logger.handlers): + HANDLER_IS_EXCLUDED: bool = excluding is not None and isinstance( + existing_handler, excluding + ) + if isinstance(existing_handler, handler_type) and not HANDLER_IS_EXCLUDED: + target_logger.removeHandler(existing_handler) + existing_handler.close() + + +def _apply_console_logging_settings(logging_settings: LoggingSettings) -> None: + """Set up logging to the console output stream.""" + # NOTE: Handlers are replaced rather than reconfigured in place, so that applying + # settings repeatedly (upon every reload) cannot accumulate duplicate handlers. + _remove_handlers_of_type(logger, logging.StreamHandler, excluding=logging.FileHandler) + + console_logging_handler: Handler = logging.StreamHandler() + console_logging_handler.setLevel(logging_settings.console.log_level) + console_logging_handler.setFormatter( + logging.Formatter("{asctime} | {name} | {levelname:^8} - {message}", style="{") + ) + + logger.addHandler(console_logging_handler) + logger.propagate = False + + +def _apply_discord_channel_logging_settings(logging_settings: LoggingSettings) -> None: + """Set up relaying of error logs to a Discord log channel.""" + _remove_handlers_of_type(logger, DiscordHandler) + + DISCORD_CHANNEL_LOGGING_SETTINGS: Final[DiscordChannelLoggingSettings | None] = ( + logging_settings.discord_channel + ) + if DISCORD_CHANNEL_LOGGING_SETTINGS is None: + logger.debug( + "No Discord log-channel webhook-URL was set, " + "so error logs will not be sent to a Discord log-channel." + ) + return + + discord_channel_logging_handler: Handler = DiscordHandler( + service_name=_discord_log_channel_identity.display_name, + webhook_url=str(DISCORD_CHANNEL_LOGGING_SETTINGS.webhook_url), + avatar_url=_discord_log_channel_identity.avatar_url, + ) + discord_channel_logging_handler.setLevel(DISCORD_CHANNEL_LOGGING_SETTINGS.log_level) + discord_channel_logging_handler.setFormatter( + logging.Formatter("{levelname} | {message}", style="{") + ) + + logger.addHandler(discord_channel_logging_handler) + + +def _apply_lowest_destination_log_level(logging_settings: LoggingSettings) -> None: + """ + Set TeX-Bot's logger to the lowest log level of any destination it writes to. + + The logger drops a record before any of its handlers see it, so each destination's + own level is set upon its handler, & the logger must let through every record that + at least one of those handlers will accept. + """ + LOG_LEVEL_NUMBERS: Final[Mapping[str, int]] = logging.getLevelNamesMapping() + + lowest_log_level: int = LOG_LEVEL_NUMBERS[logging_settings.console.log_level] + + if logging_settings.discord_channel is not None: + lowest_log_level = min( + lowest_log_level, LOG_LEVEL_NUMBERS[logging_settings.discord_channel.log_level] + ) + + logger.setLevel(lowest_log_level) + + +def _apply_discord_api_logging_settings(logging_settings: LoggingSettings) -> None: + """Set up recording of the logs emitted by the Discord API wrapper.""" + _remove_handlers_of_type(discord_logger, logging.FileHandler) + + DISCORD_API_LOGGING_SETTINGS: Final[DiscordAPILoggingSettings] = ( + logging_settings.discord_api + ) + if not DISCORD_API_LOGGING_SETTINGS.enabled: + # NOTE: The level is restored alongside the handler, so that disabling these logs + # after they have been enabled leaves the Discord API logger exactly as it began. + # Leaving a previously configured level in place would otherwise send every record + # meeting it to the root logger, now that propagation has been turned back on. + discord_logger.setLevel(logging.NOTSET) + discord_logger.propagate = True + return + + discord_api_logging_handler: Handler = logging.FileHandler( + filename=DISCORD_API_LOGGING_SETTINGS.file_name, encoding="utf-8", mode="a" + ) + discord_api_logging_handler.setFormatter( + logging.Formatter("{asctime}:{levelname}:{name}: {message}", style="{") + ) + + discord_logger.setLevel(DISCORD_API_LOGGING_SETTINGS.log_level) + discord_logger.addHandler(discord_api_logging_handler) + discord_logger.propagate = False + + +def set_discord_log_channel_identity(display_name: str, avatar_url: str | None) -> None: + """ + Relay every log sent into the Discord log channel under the given name & avatar. + + Called once TeX-Bot has logged in to Discord, which is when its own name & avatar + first become known. Applies to the handler already relaying logs, & to the one + created afresh by any later reload. + """ + global _discord_log_channel_identity # noqa: PLW0603 + + _discord_log_channel_identity = _DiscordLogChannelIdentity( + display_name=display_name, avatar_url=avatar_url + ) + + existing_handler: Handler + for existing_handler in logger.handlers: + if not isinstance(existing_handler, DiscordHandler): + continue + + existing_handler.service_name = display_name + existing_handler.avatar_url = avatar_url + + +def relay_start_up_error_to_discord_log_channel( + start_up_error: Exception, webhook_url: str +) -> None: + """ + Send an error that stopped TeX-Bot from starting up to the Discord log channel. + + Sent through a handler of its own, rather than through TeX-Bot's logger: logging + has not been set up at all when the configuration itself is invalid, & doing so + also keeps the error from being printed to the console a second time. + """ + start_up_error_handler: Handler = DiscordHandler( + service_name=_discord_log_channel_identity.display_name, + webhook_url=webhook_url, + avatar_url=_discord_log_channel_identity.avatar_url, + # NOTE: Sent once, without waiting to retry, so that an unreachable webhook + # cannot hold up the error being raised for long. + rate_limit_retry=False, + discord_timeout=3, + ) + start_up_error_handler.setFormatter( + logging.Formatter("{levelname} | {message}", style="{") + ) + + try: + start_up_error_handler.handle( + logging.makeLogRecord( + { + "name": LOGGER_NAME, + "levelno": logging.ERROR, + "levelname": "ERROR", + "msg": str(start_up_error), + } + ) + ) + finally: + start_up_error_handler.close() + + +def apply_logging_settings(logging_settings: LoggingSettings) -> None: + """ + Apply the given logging settings to every logger TeX-Bot writes to. + + Safe to call repeatedly: existing handlers are replaced rather than added to, + so reloading the configuration cannot accumulate duplicate handlers. + """ + _apply_console_logging_settings(logging_settings) + _apply_lowest_destination_log_level(logging_settings) + _apply_discord_channel_logging_settings(logging_settings) + _apply_discord_api_logging_settings(logging_settings) diff --git a/config/_messages.py b/config/_messages.py new file mode 100644 index 000000000..1df82e090 --- /dev/null +++ b/config/_messages.py @@ -0,0 +1,157 @@ +""" +Loading of the response messages that TeX-Bot sends into Discord. + +Messages are held separately from the deployment configuration: they are a body of +content rather than a set of settings, so they live in their own JSON file and are +neither validated by the settings schema nor editable through the `/config` command. +""" + +import json +import os +from pathlib import Path +from typing import TYPE_CHECKING, override + +from exceptions import ( + ImproperlyConfiguredError, + MessagesJSONFileMissingKeyError, + MessagesJSONFileValueError, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from typing import Final + + +__all__: Sequence[str] = ("MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME", "MessagesAccessor") + + +PROJECT_ROOT: Final[Path] = Path(__file__).parent.parent.resolve() + +DEFAULT_MESSAGES_FILE_NAME: Final[str] = "messages.json" + +MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME: Final[str] = "MESSAGES_FILE_PATH" + + +def _get_messages_file_path() -> Path: + """Locate the messages JSON file.""" + RAW_MESSAGES_FILE_PATH: Final[str | None] = os.getenv( + MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME + ) + + messages_file_path: Path = ( + Path(RAW_MESSAGES_FILE_PATH.strip()) + if RAW_MESSAGES_FILE_PATH + else PROJECT_ROOT / DEFAULT_MESSAGES_FILE_NAME + ) + + if not messages_file_path.is_file(): + MESSAGES_FILE_DOES_NOT_EXIST_MESSAGE: str = ( + f"{MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME} must be a path " + f"to a file that exists." + ) + raise ImproperlyConfiguredError(MESSAGES_FILE_DOES_NOT_EXIST_MESSAGE) + + return messages_file_path + + +def _load_messages_file() -> Mapping[str, object]: + """Read & decode the messages JSON file.""" + JSON_DECODING_ERROR_MESSAGE: Final[str] = ( + "Messages JSON file must contain a JSON string that can be decoded " + "into a Python dict object." + ) + + unicode_decode_error: UnicodeDecodeError + try: + raw_messages_file_contents: str = _get_messages_file_path().read_text(encoding="utf-8") + except UnicodeDecodeError as unicode_decode_error: + NOT_UTF_8_MESSAGE: Final[str] = ( + "Messages JSON file must be saved as UTF-8 text, " + f"but could not be read as UTF-8: {unicode_decode_error}" + ) + raise ImproperlyConfiguredError(NOT_UTF_8_MESSAGE) from unicode_decode_error + + json_decode_error: json.JSONDecodeError + try: + raw_messages: object = json.loads(raw_messages_file_contents) + except json.JSONDecodeError as json_decode_error: + raise ImproperlyConfiguredError(JSON_DECODING_ERROR_MESSAGE) from json_decode_error + + if not isinstance(raw_messages, dict): + raise ImproperlyConfiguredError(JSON_DECODING_ERROR_MESSAGE) + + return raw_messages + + +def _get_message_set(raw_messages: Mapping[str, object], key: str) -> frozenset[str]: + """Retrieve a single set of messages from the decoded messages file.""" + if key not in raw_messages: + raise MessagesJSONFileMissingKeyError(missing_key=key) + + value: object = raw_messages[key] + + # NOTE: Requiring a list (rather than merely something iterable) also rejects a JSON + # object, which would otherwise be accepted & silently iterated as its own keys, + # and a bare string, which would be split into one message per character. + KEY_IS_VALID: Final[bool] = isinstance(value, list) and bool(value) + if not KEY_IS_VALID: + raise MessagesJSONFileValueError(dict_key=key, invalid_value=value) + + if TYPE_CHECKING: + assert isinstance(value, list) + + return frozenset(str(single_message) for single_message in value) + + +class MessagesAccessor: + """Provides access to the response messages that TeX-Bot sends into Discord.""" + + @override + def __init__(self) -> None: + """Initialise an accessor holding no messages until they are first loaded.""" + self._welcome_messages: frozenset[str] | None = None + self._roles_messages: frozenset[str] | None = None + + @property + def is_loaded(self) -> bool: + """Whether any messages have been loaded yet.""" + return self._welcome_messages is not None and self._roles_messages is not None + + def reload(self) -> None: + """ + Load the messages JSON file, replacing any previously loaded messages. + + Both sets of messages are read before either is stored, so a malformed file + leaves any previously loaded messages untouched. + """ + RAW_MESSAGES: Final[Mapping[str, object]] = _load_messages_file() + + WELCOME_MESSAGES: Final[frozenset[str]] = _get_message_set( + RAW_MESSAGES, "welcome_messages" + ) + ROLES_MESSAGES: Final[frozenset[str]] = _get_message_set( + RAW_MESSAGES, "roles_messages" + ) + + self._welcome_messages = WELCOME_MESSAGES + self._roles_messages = ROLES_MESSAGES + + def _get_loaded(self, messages: frozenset[str] | None) -> frozenset[str]: + """Return the given set of messages, raising if they have not been loaded.""" + if messages is None: + MESSAGES_NOT_LOADED_MESSAGE: str = ( + "Messages cannot be accessed before they have been loaded." + ) + raise RuntimeError(MESSAGES_NOT_LOADED_MESSAGE) + + return messages + + @property + def welcome_messages(self) -> frozenset[str]: + """The set of messages welcoming a new member into the community group.""" + return self._get_loaded(self._welcome_messages) + + @property + def roles_messages(self) -> frozenset[str]: + """The set of messages describing the opt-in roles that a member can request.""" + return self._get_loaded(self._roles_messages) diff --git a/config/_schema.py b/config/_schema.py new file mode 100644 index 000000000..2c0e43000 --- /dev/null +++ b/config/_schema.py @@ -0,0 +1,920 @@ +""" +Pydantic schema declaring every configuration setting TeX-Bot understands. + +This module is the single source of truth for the deployment configuration: +the shape of `tex-bot-deployment.yaml`, the type & constraints of every setting, +each setting's default value, and the metadata used to render the `/config` command +(help text, whether a restart is required, and whether the value is a secret). + +Nothing in this module reads or writes files; it only describes & validates data. + +NOTE: Annotations here are deliberately *not* deferred into `if TYPE_CHECKING:` blocks. +Pydantic evaluates field annotations at model-build time, +so every name used within a field annotation must be importable at runtime. +""" + +import datetime +import os +import re +from enum import StrEnum +from pathlib import Path +from typing import TYPE_CHECKING, Annotated, Literal, NamedTuple, get_args + +from pydantic import ( + AfterValidator, + BaseModel, + BeforeValidator, + ConfigDict, + Field, + HttpUrl, + SecretStr, # NOTE: Pydantic resolves field annotations at runtime # noqa: TC002 + model_validator, +) + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, Sequence + from typing import Final + + from pydantic.fields import FieldInfo + + +__all__: Sequence[str] = ( + "AutoCookieCheckingSettings", + "CommandsSettings", + "CommunityGroupSettings", + "ConfigSettingMetadata", + "ConsoleLoggingSettings", + "DiscordAPILoggingSettings", + "DiscordChannelLoggingSettings", + "DiscordSettings", + "DiscordWebhookURL", + "LinksSettings", + "LogLevel", + "LoggingSettings", + "MSLSettings", + "PingCommandSettings", + "ReminderSettings", + "RemindersSettings", + "SendIntroductionRemindersFlag", + "SendIntroductionRemindersSettings", + "SettingsSchema", + "StatsCommandSettings", + "StrikeCommandSettings", + "get_settings_metadata", + "nested_settings_model_of", + "setting_names_within", +) + + +class LogLevel(StrEnum): + """The set of valid values for any log-level configuration setting.""" + + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + CRITICAL = "CRITICAL" + + +SendIntroductionRemindersFlag = Literal["once", "interval", False] + + +def _to_kebab_case(field_name: str) -> str: + """Convert a Python field name into the kebab-case key used within the YAML file.""" + return field_name.replace("_", "-") + + +def _parse_log_level(value: object) -> object: + """Normalise a raw log-level value, matching it case & punctuation agnostically.""" + if not isinstance(value, str): + return value + + return value.upper().strip(" \n\t-_.") + + +def _parse_send_introduction_reminders_flag(value: object) -> object: + """ + Normalise a raw send-introduction-reminders value into its canonical form. + + Truthy boolean-like values are treated as `"once"`, + because sending a single reminder is the historic behaviour of enabling this setting. + """ + if isinstance(value, bool): + return "once" if value else False + + if not isinstance(value, str): + # NOTE: Pydantic's `Literal` would otherwise accept `0` as `False` (though never + # `1` as `once`), so `enabled: 0` would silently disable introduction reminders + # while the `enabled: 1` its author would pair it with was rejected. + NON_STRING_FLAG_MESSAGE: str = ( + "Value should be 'once', 'interval', or a boolean ('true'/'false')" + ) + # NOTE: Deliberately a `ValueError` despite describing a wrong type: Pydantic + # converts only `ValueError` & `AssertionError` into validation errors, so a + # `TypeError` would propagate uncaught & abandon the whole reload. + raise ValueError(NON_STRING_FLAG_MESSAGE) # noqa: TRY004 + + NORMALISED_VALUE: str = value.lower().strip() + + if NORMALISED_VALUE in ("once", "interval"): + return NORMALISED_VALUE + + if NORMALISED_VALUE in ("true", "yes", "on", "1"): + return "once" + + if NORMALISED_VALUE in ("false", "no", "off", "0"): + return False + + return value + + +def _parse_organisation_id(value: object) -> object: + """Convert an organisation ID written without quotes into the text it is meant as.""" + # NOTE: An exact type check, rather than `isinstance()`, because ruamel.yaml reads + # `01234`, `1_234` & `0x1234` as subclasses of `int`. Converting one of those would + # silently produce a different ID, so they are left to be rejected as non-text. + return str(value) if type(value) is int else value + + +_TIME_DELTA_MATCHER: re.Pattern[str] = re.compile( + r"\A(?:(?P(?:\d*\.)?\d+)w)?" + r"(?:(?P(?:\d*\.)?\d+)d)?" + r"(?:(?P(?:\d*\.)?\d+)h)?" + r"(?:(?P(?:\d*\.)?\d+)m)?" + r"(?:(?P(?:\d*\.)?\d+)s)?\Z", + re.IGNORECASE, +) + +# NOTE: Discord will not disable a member's communication more than 28 days into the +# future, & rejects any attempt to do so. +# See . +MAXIMUM_DISCORD_TIMEOUT_DURATION: Final[datetime.timedelta] = datetime.timedelta(days=28) + + +def _parse_time_delta(value: object) -> object: + """ + Parse a delay/interval string, in the format `wdhms`. + + NOTE: Time resolutions must be given in descending order of size + (so `1h30m` is accepted, whereas `30m1h` is not). + + NOTE: Capital letters & spaces are ignored (so `1H 30M` is accepted), as they were + when these settings were read from environment variables. + + NOTE: A deviation from the previous StrictYAML implementation, which required time + resolutions in *ascending* order of size, so accepted `30m1h` but rejected `1h30m`. + + NOTE: A further deviation from that previous implementation: + an empty string is rejected rather than silently parsed as a zero-length duration. + Durations that may not be zero-length are declared as `PositiveTimeDelta` + (or `DiscordTimeoutDuration`, which is additionally bounded above); + this parser itself accepts a zero-length duration written explicitly (`0s`). + """ + if isinstance(value, datetime.timedelta): + return value + + if not isinstance(value, str): + # NOTE: Pydantic would otherwise accept a bare number as a count of seconds, so + # `timeout-duration: 24` would silently mean 24 seconds rather than the 24 hours + # its author almost certainly intended. Requiring a unit removes the ambiguity, + # and matches the string `'24'` already being rejected for the same reason. + NON_STRING_TIME_DELTA_MESSAGE: str = ( + "Value should be a delay/interval string, in the format " + "'wdhms', including the unit of each part" + ) + # NOTE: Deliberately a `ValueError` despite describing a wrong type: Pydantic + # converts only `ValueError` & `AssertionError` into validation errors, so a + # `TypeError` would propagate uncaught & abandon the whole reload. + raise ValueError(NON_STRING_TIME_DELTA_MESSAGE) # noqa: TRY004 + + match: re.Match[str] | None = _TIME_DELTA_MATCHER.fullmatch("".join(value.split())) + if match is None or not any(match.groupdict().values()): + # NOTE: Raising here (rather than deferring to Pydantic's own timedelta parsing) + # keeps the set of accepted values identical to the documented format: + # Pydantic would otherwise also accept ISO-8601 durations & `HH:MM:SS` strings. + INVALID_TIME_DELTA_MESSAGE: str = ( + "Value should be a delay/interval string, in the format " + "'wdhms' " + "(with time resolutions given in descending order of size)" + ) + raise ValueError(INVALID_TIME_DELTA_MESSAGE) + + overflow_error: OverflowError + try: + return datetime.timedelta( + **{ + time_resolution_name: float(raw_time_resolution_value) + for time_resolution_name, raw_time_resolution_value in ( + match.groupdict().items() + ) + if raw_time_resolution_value + } + ) + except OverflowError as overflow_error: + # NOTE: Converted to a `ValueError` for the same reason as above: Pydantic would + # otherwise let the `OverflowError` propagate uncaught & abandon the whole reload. + TOO_LONG_TIME_DELTA_MESSAGE: str = ( + "Value should be a delay/interval short enough to be held as a length of time" + ) + raise ValueError(TOO_LONG_TIME_DELTA_MESSAGE) from overflow_error + + +def _ensure_positive_time_delta(value: datetime.timedelta) -> datetime.timedelta: + """ + Ensure the given duration is longer than zero. + + A zero-length interval would cause the recurring task looping upon it to run + continuously, without ever pausing between one execution & the next. A zero-length + moderation timeout would expire the instant it was applied, silently applying no + moderation action at all. + """ + if value <= datetime.timedelta(0): + NON_POSITIVE_TIME_DELTA_MESSAGE: str = ( + "Value should be a delay/interval string describing a duration longer than zero" + ) + raise ValueError(NON_POSITIVE_TIME_DELTA_MESSAGE) + + return value + + +def _ensure_within_discord_timeout_limit( + value: datetime.timedelta, +) -> datetime.timedelta: + """ + Ensure the given duration is one that Discord will actually apply as a timeout. + + Pycord performs no check of its own before sending the request, so an over-long + duration would otherwise be caught only by Discord itself, surfacing as an opaque + HTTP error at the moment a committee-member tried to apply a strike. + """ + if value > MAXIMUM_DISCORD_TIMEOUT_DURATION: + EXCESSIVE_TIMEOUT_DURATION_MESSAGE: str = ( + "Value should be a duration string describing a duration " + "no longer than 28 days (the longest timeout Discord will apply)" + ) + raise ValueError(EXCESSIVE_TIMEOUT_DURATION_MESSAGE) + + return value + + +def _ensure_discord_webhook_url(value: HttpUrl) -> HttpUrl: + """Ensure the given URL refers to a Discord webhook.""" + if not str(value).startswith("https://discord.com/api/webhooks/"): + NOT_A_DISCORD_WEBHOOK_URL_MESSAGE: str = ( + "Value should be a Discord webhook URL " + "(beginning with 'https://discord.com/api/webhooks/')" + ) + raise ValueError(NOT_A_DISCORD_WEBHOOK_URL_MESSAGE) + + return value + + +def _ensure_matches( + value: SecretStr, matcher: re.Pattern[str], expected_description: str +) -> SecretStr: + """ + Ensure the given secret value matches the given pattern. + + The secret value itself is never included within the raised error message. + """ + if matcher.fullmatch(value.get_secret_value()) is None: + NON_MATCHING_VALUE_MESSAGE: str = f"Value should be {expected_description}" + raise ValueError(NON_MATCHING_VALUE_MESSAGE) + + return value + + +def _ensure_unique(value: tuple[str, ...]) -> tuple[str, ...]: + """Ensure the given sequence of values contains no duplicates.""" + if len(set(value)) != len(value): + DUPLICATE_VALUES_MESSAGE: str = "Value should be a sequence of unique values" + raise ValueError(DUPLICATE_VALUES_MESSAGE) + + return value + + +type TimeDelta = Annotated[datetime.timedelta, BeforeValidator(_parse_time_delta)] +type PositiveTimeDelta = Annotated[ + datetime.timedelta, + BeforeValidator(_parse_time_delta), + AfterValidator(_ensure_positive_time_delta), +] +type DiscordTimeoutDuration = Annotated[ + datetime.timedelta, + BeforeValidator(_parse_time_delta), + AfterValidator(_ensure_positive_time_delta), + AfterValidator(_ensure_within_discord_timeout_limit), +] +type UniqueStrSequence = Annotated[tuple[str, ...], AfterValidator(_ensure_unique)] +type DiscordWebhookURL = Annotated[HttpUrl, AfterValidator(_ensure_discord_webhook_url)] +type DiscordSnowflake = Annotated[int, Field(ge=10**16, lt=10**20)] +type NormalisedLogLevel = Annotated[LogLevel, BeforeValidator(_parse_log_level)] + + +class _BaseSettingsSchema(BaseModel): + """Common configuration shared by every section of the settings schema.""" + + model_config = ConfigDict( + alias_generator=_to_kebab_case, + extra="forbid", + frozen=True, + # NOTE: Pydantic's default regex engine is Rust's, which rejects Python-only anchors + # (such as `\Z`). Using Python's own engine keeps every pattern below identical to + # the one it replaces, rather than requiring subtly different equivalents. + regex_engine="python-re", + ) + + +class ConsoleLoggingSettings(_BaseSettingsSchema): + """Settings controlling how logs are emitted to the console output stream.""" + + log_level: NormalisedLogLevel = Field( + default=LogLevel.INFO, + description=( + "The minimum level that logs must meet " + "in order to be logged to the console output stream." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class DiscordChannelLoggingSettings(_BaseSettingsSchema): + """Settings controlling how logs are relayed to a Discord log channel.""" + + webhook_url: DiscordWebhookURL = Field( + description=( + "The webhook URL of the Discord text channel where error logs should be sent.\n" + "Error logs will always be sent to the console; " + "this setting allows them to also be sent to a Discord log channel." + ), + json_schema_extra={"requires_restart": False, "secret": True}, + ) + log_level: NormalisedLogLevel = Field( + default=LogLevel.WARNING, + description=( + "The minimum level that logs must meet " + "in order to be logged to the Discord log channel." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class DiscordAPILoggingSettings(_BaseSettingsSchema): + """Settings controlling how logs emitted by the Discord API wrapper are handled.""" + + enabled: bool = Field( + default=False, + description="Whether logs emitted by the Discord API wrapper should be recorded.", + json_schema_extra={"requires_restart": False, "secret": False}, + ) + log_level: NormalisedLogLevel = Field( + default=LogLevel.INFO, + description=( + "The minimum level that Discord API logs must meet in order to be recorded." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + file_name: str = Field( + default="discord.log", + min_length=1, + description=( + "The name of the file that Discord API logs should be written to.\n" + "The folder holding this file must already exist." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + @model_validator(mode="after") + def _ensure_log_file_can_be_written(self) -> DiscordAPILoggingSettings: + """ + Refuse a log file that could not be opened, once recording is enabled. + + Checked while validating, rather than only when the file is opened, so that a + change naming an unusable file is refused before it is written or applied. + """ + if not self.enabled: + return self + + LOG_FILE_PATH: Final[Path] = Path(self.file_name) + + if not LOG_FILE_PATH.parent.is_dir(): + MISSING_FOLDER_MESSAGE: Final[str] = ( + f"The folder {str(LOG_FILE_PATH.parent)!r} does not exist, " + "so the Discord API log file cannot be created within it." + ) + raise ValueError(MISSING_FOLDER_MESSAGE) + + if LOG_FILE_PATH.is_dir(): + FOLDER_NOT_FILE_MESSAGE: Final[str] = ( + f"{self.file_name!r} is a folder, so it cannot be used as the log file." + ) + raise ValueError(FOLDER_NOT_FILE_MESSAGE) + + if not os.access( + LOG_FILE_PATH if LOG_FILE_PATH.exists() else LOG_FILE_PATH.parent, os.W_OK + ): + NOT_WRITABLE_MESSAGE: Final[str] = ( + f"TeX-Bot is not allowed to write to {self.file_name!r}." + ) + raise ValueError(NOT_WRITABLE_MESSAGE) + + return self + + +class LoggingSettings(_BaseSettingsSchema): + """Settings controlling every logging destination TeX-Bot can write to.""" + + console: ConsoleLoggingSettings = Field(default_factory=ConsoleLoggingSettings) + discord_channel: DiscordChannelLoggingSettings | None = Field( + default=None, + description=( + "Settings for relaying error logs to a Discord log channel. " + "Omit this section entirely to disable Discord log-channel logging." + ), + ) + discord_api: DiscordAPILoggingSettings = Field(default_factory=DiscordAPILoggingSettings) + + +class DiscordSettings(_BaseSettingsSchema): + """Settings describing how TeX-Bot connects to Discord.""" + + bot_token: Annotated[ + SecretStr, + AfterValidator( + lambda token: _ensure_matches( + token, + # NOTE: Every segment is base64url-encoded, so any of them may contain + # `-` or `_`: the middle segment (an encoded timestamp) routinely does. + re.compile( + r"\A([A-Za-z0-9_-]{24,26})\.([A-Za-z0-9_-]{6})\.([A-Za-z0-9_-]{27,38})\Z" + ), + "a Discord bot token", + ) + ), + ] = Field( + description=( + "The Discord token for the bot you created (available on your bot's page " + "within the Discord developer portal: " + ")." + ), + json_schema_extra={"requires_restart": True, "secret": True}, + ) + main_guild_id: DiscordSnowflake = Field( + description="The ID of your community group's main Discord guild.", + json_schema_extra={"requires_restart": True, "secret": False}, + ) + + +class LinksSettings(_BaseSettingsSchema): + """Settings holding the external links referenced within TeX-Bot's messages.""" + + purchase_membership: HttpUrl | None = Field( + default=None, + description=( + "The link to the page where guests can purchase a full membership " + "to join your community group." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + membership_perks: HttpUrl | None = Field( + default=None, + description=( + "The link to the page where guests can find out information about the perks " + "they will receive once they purchase a membership to your community group." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + moderation_policy: HttpUrl | None = Field( + default=None, + description="The link to your group's Discord guild moderation policy document.", + json_schema_extra={"requires_restart": False, "secret": False}, + ) + custom_discord_invite_link: HttpUrl | None = Field( + default=None, + description=( + "A custom invite link to your group's Discord guild, " + "used in place of one generated by TeX-Bot." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class AutoCookieCheckingSettings(_BaseSettingsSchema): + """Settings controlling the automatic checking of the MSL authentication cookie.""" + + enabled: bool = Field( + default=False, + description=( + "Whether the MSL authentication cookie should be automatically checked " + "to determine whether it is still valid." + ), + json_schema_extra={"requires_restart": True, "secret": False}, + ) + interval: PositiveTimeDelta = Field( + default=datetime.timedelta(minutes=10), + description="The interval of time between checking the MSL authentication cookie.", + json_schema_extra={"requires_restart": True, "secret": False}, + ) + + +class MSLSettings(_BaseSettingsSchema): + """Settings describing how TeX-Bot authenticates with your group's MSL website.""" + + organisation_id: Annotated[str | None, BeforeValidator(_parse_organisation_id)] = Field( + default=None, + pattern=r"\A\d{4,5}\Z", + description="The ID of your community group's organisation on your MSL website.", + json_schema_extra={"requires_restart": False, "secret": False}, + ) + auth_cookie: ( + Annotated[ + SecretStr, + AfterValidator( + lambda cookie: _ensure_matches( + cookie, + re.compile(r"\A[\w-]{512,1024}\Z"), + "an MSL authentication cookie", + ) + ), + ] + | None + ) = Field( + default=None, + description=( + "The MSL authentication session cookie.\n" + "This should authenticate TeX-Bot to view your group's members-list, " + "as if it were logged in to the website as a committee member.\n" + "This can be extracted from your web-browser after manually logging in " + "to view your members-list yourself: " + "it will probably be listed as a cookie named `.AspNet.SharedCookie`." + ), + json_schema_extra={"requires_restart": False, "secret": True}, + ) + auto_cookie_checking: AutoCookieCheckingSettings = Field( + default_factory=AutoCookieCheckingSettings + ) + + +class CommunityGroupSettings(_BaseSettingsSchema): + """Settings describing the community group that TeX-Bot is deployed for.""" + + full_name: str | None = Field( + default=None, + # NOTE: Only characters that cannot form a Discord mention or Markdown formatting are allowed, because this is substituted into messages that TeX-Bot sends + pattern=r"\A[A-Za-z0-9 '&!?:,.#%\"-]{1,50}\Z", + description=( + "The full name of your community group; do **NOT** use an abbreviation.\n" + "This is substituted into many error/welcome messages " + "sent into your Discord guild by TeX-Bot.\n" + "It may only contain letters, numbers, spaces & the characters " + "`' & ! ? : , . # % \" -`.\n" + "If this is not set, the group's full name will be retrieved " + "from the name of your group's Discord guild." + ), + # NOTE: Requires a restart because the name of the ID argument to `/make-member` + # is derived from this, & so is fixed when that command is registered. + json_schema_extra={"requires_restart": True, "secret": False}, + ) + short_name: str | None = Field( + default=None, + pattern=r"\A(?!.*['&!?:,.#%\"-]['&!?:,.#%\"-].*)(?:[A-Za-z0-9'&!?:,.#%\"-]+)\Z", + description=( + "The short colloquial name of your community group; it is recommended " + "that you set this to be an abbreviation of your group's name.\n" + "If this is not set, the group's short name will be determined " + "from your group's full name." + ), + # NOTE: Requires a restart because the descriptions of the `/stats` commands are + # derived from this, & so are fixed when those commands are registered. + json_schema_extra={"requires_restart": True, "secret": False}, + ) + membership_dependent_roles: UniqueStrSequence = Field( + # NOTE: Defaults to no roles, rather than being absent, so that consumers can + # always iterate it or test membership of it without a null check first. + default=(), + description=( + "The names of the roles that should only be held " + "by members of your community group." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + links: LinksSettings = Field(default_factory=LinksSettings) + msl: MSLSettings = Field(default_factory=MSLSettings) + + +class PingCommandSettings(_BaseSettingsSchema): + """Settings controlling the behaviour of the `/ping` command.""" + + easter_egg_probability: float = Field( + default=0.01, + ge=0, + le=1, + description=( + "The probability that the rarer ping command response will be sent " + "instead of the normal one." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class StatsCommandSettings(_BaseSettingsSchema): + """Settings controlling the behaviour of the `/stats` command.""" + + lookback_days: float = Field( + default=30.0, + ge=5, + le=1826, + description=( + "The number of days to look back over messages sent, to generate statistics data." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + displayed_roles: UniqueStrSequence = Field( + default=( + "Committee", + "Committee-Elect", + "Student Rep", + "Member", + "Guest", + "Server Booster", + "Foundation Year", + "First Year", + "Second Year", + "Final Year", + "Year In Industry", + "Year Abroad", + "PGT", + "PGR", + "Alumnus/Alumna", + "Postdoc", + "Quiz Victor", + ), + description=( + "The names of the roles to gather statistics about, to display in bar charts." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + @property + def lookback_period(self) -> datetime.timedelta: + """ + The period of time to look back over messages sent, to generate statistics data. + + Held within the configuration file as a plain number of days, because that reads + far more naturally than a duration string for a value of this size. + """ + return datetime.timedelta(days=self.lookback_days) + + +class StrikeCommandSettings(_BaseSettingsSchema): + """Settings controlling the behaviour of the `/strike` command.""" + + performed_manually_warning_location: str = Field( + default="DM", + min_length=1, + description=( + "The name of the channel that warning messages will be sent to, when a " + "committee-member manually applies a moderation action " + "(instead of using the `/strike` command).\n" + "This can be the name of **ANY** Discord channel " + "(so the offending person *will* be able to see these messages " + "if a public channel is chosen), or the value `DM` " + "(which indicates the messages will be sent to the committee-member's DMs)." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + timeout_duration: DiscordTimeoutDuration = Field( + default=datetime.timedelta(hours=24), + description=( + "The amount of time to timeout a user for, when using the `/strike` command.\n" + "Discord will not apply a timeout longer than 28 days." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + reported_message_destination_channel: str = Field( + default="discord", + min_length=1, + description=( + "The name of the channel that reported messages should be sent to for review." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class CommandsSettings(_BaseSettingsSchema): + """Settings controlling the behaviour of TeX-Bot's individual commands.""" + + ping: PingCommandSettings = Field(default_factory=PingCommandSettings) + stats: StatsCommandSettings = Field(default_factory=StatsCommandSettings) + strike: StrikeCommandSettings = Field(default_factory=StrikeCommandSettings) + + +class SendIntroductionRemindersSettings(_BaseSettingsSchema): + """Settings controlling the reminders sent to Discord members that are not inducted.""" + + enabled: Annotated[ + SendIntroductionRemindersFlag, + BeforeValidator(_parse_send_introduction_reminders_flag), + ] = Field( + default="once", + description=( + "Whether introduction reminders will be sent to Discord members " + "that are not inducted, saying that they need to send an introduction " + "to be allowed access.\n" + "Use `once` to send a single reminder, `interval` to send them repeatedly, " + "or `false` to disable them entirely." + ), + json_schema_extra={"requires_restart": True, "secret": False}, + ) + delay: TimeDelta = Field( + default=datetime.timedelta(hours=40), + description=( + "How long to wait after a user joins your guild, before sending them " + "the first/only message reminding them to send an introduction.\n" + "Is ignored if `enabled` **=** `false`." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + interval: PositiveTimeDelta = Field( + default=datetime.timedelta(hours=6), + description=( + "The interval of time between sending out reminders to Discord members " + "that are not inducted.\n" + "Is ignored unless `enabled` **=** `interval`." + ), + json_schema_extra={"requires_restart": True, "secret": False}, + ) + + +class ReminderSettings(_BaseSettingsSchema): + """Settings controlling the reminders sent to Discord members that have been inducted.""" + + enabled: bool = Field( + default=True, + description=( + "Whether reminders will be sent to Discord members that have been inducted, " + "saying that they can get opt-in roles. " + "(This message will only be sent once per Discord member.)" + ), + json_schema_extra={"requires_restart": True, "secret": False}, + ) + delay: TimeDelta = Field( + default=datetime.timedelta(hours=40), + description=( + "How long to wait after a user is inducted, before sending them the message " + "telling them to get some opt-in roles.\n" + "Is ignored if `enabled` **=** `false`." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + interval: PositiveTimeDelta = Field( + default=datetime.timedelta(hours=24), + description=( + "The interval of time between checking for Discord members " + "that should be sent a get-roles reminder.\n" + "Is ignored if `enabled` **=** `false`." + ), + json_schema_extra={"requires_restart": True, "secret": False}, + ) + + +class RemindersSettings(_BaseSettingsSchema): + """Settings controlling every kind of reminder that TeX-Bot can send.""" + + send_introduction_reminders: SendIntroductionRemindersSettings = Field( + default_factory=SendIntroductionRemindersSettings + ) + send_get_roles_reminders: ReminderSettings = Field(default_factory=ReminderSettings) + + +class SettingsSchema(_BaseSettingsSchema): + """The complete set of configuration settings that TeX-Bot understands.""" + + logging: LoggingSettings = Field(default_factory=LoggingSettings) + discord: DiscordSettings + community_group: CommunityGroupSettings = Field(default_factory=CommunityGroupSettings) + commands: CommandsSettings = Field(default_factory=CommandsSettings) + reminders: RemindersSettings = Field(default_factory=RemindersSettings) + auto_add_committee_to_threads: bool = Field( + default=True, + description=( + "Whether committee members should be automatically added " + "to any newly created threads." + ), + json_schema_extra={"requires_restart": False, "secret": False}, + ) + + +class ConfigSettingMetadata(NamedTuple): + """The information describing a single configuration setting to a human.""" + + description: str | None + requires_restart: bool + secret: bool + holds_text: bool + + # NOTE: The key path of the optional section that cannot be used without this setting, + # if there is one. Removing this setting removes the whole of that section with it. + required_by_optional_section: str | None = None + + +def _holds_text(annotation: object) -> bool: + """ + Whether the given field annotation accepts text, & only text. + + Used to keep a value that merely looks like a number + (an organisation ID of `1234`, for example) as the text it is declared to be. + """ + if annotation is str: + return True + + ANNOTATION_ARGUMENTS: Final[tuple[object, ...]] = get_args(annotation) + + # NOTE: Every member of the annotation must be checked, rather than merely testing + # whether it contains `str`, so that a *sequence* of strings is not mistaken for one. + return bool(ANNOTATION_ARGUMENTS) and all( + annotation_argument is str or annotation_argument is type(None) + for annotation_argument in ANNOTATION_ARGUMENTS + ) + + +def nested_settings_model_of(field: FieldInfo) -> type[BaseModel] | None: + """ + Return the settings section that the given field holds, if it holds one at all. + + A field's annotation may be a union (an optional section, for example), so every + member of it must be searched to find the nested model it may contain. + """ + return next( + ( + annotation_argument + for annotation_argument in (get_args(field.annotation) or (field.annotation,)) + if isinstance(annotation_argument, type) + and issubclass(annotation_argument, BaseModel) + ), + None, + ) + + +def _walk_settings_metadata( + model: type[BaseModel], prefix: str = "", optional_section: str | None = None +) -> Iterator[tuple[str, ConfigSettingMetadata]]: + """ + Yield the metadata of every individual setting declared within the given model. + + The given model is held within the given optional section, if it is held within one. + """ + field_name: str + field: FieldInfo + for field_name, field in model.model_fields.items(): + KEY_PATH: str = f"{prefix}{field_name.replace('_', '-')}" + + nested_model: type[BaseModel] | None = nested_settings_model_of(field) + if nested_model is not None: + yield from _walk_settings_metadata( + nested_model, + prefix=f"{KEY_PATH}:", + optional_section=( + KEY_PATH if type(None) in get_args(field.annotation) else optional_section + ), + ) + continue + + EXTRA: Mapping[str, object] = ( + field.json_schema_extra if isinstance(field.json_schema_extra, dict) else {} + ) + + yield ( + KEY_PATH, + ConfigSettingMetadata( + description=field.description, + requires_restart=EXTRA.get("requires_restart") is True, + secret=EXTRA.get("secret") is True, + holds_text=_holds_text(field.annotation), + required_by_optional_section=( + optional_section if field.is_required() else None + ), + ), + ) + + +def setting_names_within(model: type[BaseModel], prefix: str = "") -> Iterator[str]: + """ + Yield the key path of every individual setting declared within the given model. + + Derived from the same walk that produces the settings metadata, so that a name + yielded here is always one that the `/config` command recognises. + """ + key_path: str + for key_path, _ in _walk_settings_metadata(model, prefix=prefix): + yield key_path + + +def get_settings_metadata() -> Mapping[str, ConfigSettingMetadata]: + """ + Return the metadata of every configuration setting, keyed by its key path. + + Derived from the schema itself, so that the help text, restart requirements & + secrecy of each setting cannot drift out of step with the settings that exist. + """ + return dict(_walk_settings_metadata(SettingsSchema)) diff --git a/db/_settings.py b/db/_settings.py index bdbd07ea9..894c979c9 100644 --- a/db/_settings.py +++ b/db/_settings.py @@ -30,10 +30,14 @@ if IMPORTED_BY_MYPY_OR_PYTEST: SECRET_KEY = "unsecure-secret-key" # noqa: S105 else: - from config import settings + import config + + # NOTE: Django's own tools (such as `django-admin makemigrations`) import these settings without TeX-Bot's configuration having been loaded first, so it must be loaded here + if not config.settings.is_loaded: + config.reload_settings() # SECURITY WARNING: keep the secret key used in production secret! - SECRET_KEY = settings.DISCORD_BOT_TOKEN + SECRET_KEY = config.settings.discord.bot_token.get_secret_value() # Application Definition diff --git a/exceptions/__init__.py b/exceptions/__init__.py index fedc9a8a0..a0173935c 100644 --- a/exceptions/__init__.py +++ b/exceptions/__init__.py @@ -15,6 +15,7 @@ "InvalidActionDescriptionError", "InvalidActionTargetError", "InvalidMessagesJSONFileError", + "InvalidSettingsFileError", "MSLMembershipError", "MemberRoleDoesNotExistError", "MessagesJSONFileMissingKeyError", @@ -24,7 +25,12 @@ "RoleDoesNotExistError", "RolesChannelDoesNotExistError", "RulesChannelDoesNotExistError", + "SettingsFileChangedError", + "SettingsFileNotFoundError", + "SettingsNotLoadedError", + "SettingsValidationError", "StrikeTrackingError", + "UnknownSettingError", ) lazy from collections.abc import Sequence @@ -52,4 +58,12 @@ MessagesJSONFileValueError, ) from .msl import MSLMembershipError +from .settings import ( + InvalidSettingsFileError, + SettingsFileChangedError, + SettingsFileNotFoundError, + SettingsNotLoadedError, + SettingsValidationError, + UnknownSettingError, +) from .strike import NoAuditLogsStrikeTrackingError, StrikeTrackingError diff --git a/exceptions/config_changes.py b/exceptions/config_changes.py index e0de275bf..ea99338d1 100644 --- a/exceptions/config_changes.py +++ b/exceptions/config_changes.py @@ -12,12 +12,12 @@ class ImproperlyConfiguredError(BaseTeXBotError, Exception): - """Exception class to raise when environment variables are not correctly provided.""" + """Exception class to raise when a configuration value is not correctly provided.""" @classproperty @override def DEFAULT_MESSAGE(cls) -> str: - return "One or more provided environment variable values are invalid." + return "One or more provided configuration values are invalid." class RestartRequiredDueToConfigChange(BaseTeXBotError, Exception): # noqa: N818 @@ -33,6 +33,6 @@ def __init__( self, message: str | None = None, changed_settings: AbstractSet[str] | None = None ) -> None: """Initialise an Exception to apply configuration changes.""" - self.changed_settings: AbstractSet[str] | None = changed_settings or set() + self.changed_settings: AbstractSet[str] = changed_settings or set() super().__init__(message) diff --git a/exceptions/settings.py b/exceptions/settings.py new file mode 100644 index 000000000..eaf8cd606 --- /dev/null +++ b/exceptions/settings.py @@ -0,0 +1,81 @@ +"""Custom exception classes related to reading & changing the deployment configuration.""" + +from typing import TYPE_CHECKING, override + +from typed_classproperties import classproperty + +from .base import BaseTeXBotError +from .config_changes import ImproperlyConfiguredError + +if TYPE_CHECKING: + from collections.abc import Sequence + +__all__: Sequence[str] = ( + "InvalidSettingsFileError", + "SettingsFileChangedError", + "SettingsFileNotFoundError", + "SettingsNotLoadedError", + "SettingsValidationError", + "UnknownSettingError", +) + + +class SettingsFileNotFoundError(ImproperlyConfiguredError): + """Exception class to raise when no deployment configuration file could be located.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "No deployment configuration file could be located." + + +class InvalidSettingsFileError(ImproperlyConfiguredError): + """Exception class to raise when the deployment configuration file could not be read.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "The deployment configuration file could not be read." + + +class SettingsNotLoadedError(BaseTeXBotError, Exception): + """Exception class to raise when configuration is accessed before it has been loaded.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "Configuration cannot be accessed before it has been loaded." + + +class SettingsValidationError(ImproperlyConfiguredError): + """Exception class to raise when the configuration file contains invalid settings.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "The configuration file contains invalid settings." + + +class UnknownSettingError(BaseTeXBotError, Exception): + """Exception class to raise when a setting that the schema does not declare is named.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "No configuration setting is named that." + + @override + def __init__(self, setting_name: str) -> None: + """Initialise a new UnknownSettingError for the given setting name.""" + self.setting_name: str = setting_name + + super().__init__(f"No configuration setting is named {setting_name!r}.") + + +class SettingsFileChangedError(BaseTeXBotError, Exception): + """Exception class to raise when the configuration file has been edited by hand.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "The configuration file has been changed since TeX-Bot last loaded it." diff --git a/main.py b/main.py index 29b7d9eaf..c4c456929 100755 --- a/main.py +++ b/main.py @@ -2,7 +2,7 @@ """ The main entrypoint into the running of TeX-Bot. -It loads the settings values from the .env file/the environment variables, +It loads the settings values from the deployment configuration file, then ensures the Django database is correctly migrated to the latest version and finally begins the asynchronous running process for TeX-Bot. """ @@ -29,7 +29,7 @@ def _run_bot() -> NoReturn: # NOTE: See https://github.com/CSSUoB/TeX-Bot-Py-V2/issues/261 - bot.run(settings["DISCORD_BOT_TOKEN"]) + bot.run(settings.discord.bot_token.get_secret_value()) raise SystemExit(0 if bot.EXIT_WAS_DUE_TO_KILL_COMMAND else 1) diff --git a/pyproject.toml b/pyproject.toml index 2eb219a1c..635be3fd2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,10 +27,11 @@ main = [ "mplcyberpunk>=0.7", "parsedatetime>=2.6", "py-cord>=2.8", + "pydantic>=2.13", "python-dotenv>=1.0", "python-logging-discord-handler>=0.1", - "typed_classproperties>=1.2", - "validators>=0.34" + "ruamel-yaml>=0.19", + "typed_classproperties>=1.2" ] pre-commit = ["prek>=0.5.3"] test = ["pytest>=9", "pytest-cov>=6.1"] @@ -77,7 +78,7 @@ enable_error_code = [ extra_checks = true mypy_path = "stubs" no_implicit_reexport = true -plugins = ["mypy_django_plugin.main"] +plugins = ["mypy_django_plugin.main", "pydantic.mypy"] strict_bytes = true strict_equality = true strict_equality_for_none = true @@ -111,6 +112,7 @@ plugins.ul-style.style = "asterisk" [tool.pytest] filterwarnings = ["ignore:'audioop':DeprecationWarning"] strict = true +testpaths = ["tests"] [tool.ruff] extend-exclude = ["db/**/migrations/"] diff --git a/stubs/discord/commands/core.pyi b/stubs/discord/commands/core.pyi index 697d40c0f..0a1d82e0a 100644 --- a/stubs/discord/commands/core.pyi +++ b/stubs/discord/commands/core.pyi @@ -1,5 +1,6 @@ __all__: Sequence[str] = ( "ApplicationCommand", + "CommandCallback", "MessageCommand", "SlashCommand", "SlashCommandGroup", @@ -11,8 +12,14 @@ __all__: Sequence[str] = ( "user_command", ) -from collections.abc import Awaitable, Callable, Sequence -from typing import override +from collections.abc import Awaitable, Callable, Coroutine, Sequence +from typing import Protocol, overload, override + +# NOTE: The undecorated function that a command runs when it is invoked. +class CommandCallback(Protocol): + __name__: str + + def __call__(self, *args: object, **kwargs: object) -> Coroutine[object, object, None]: ... def slash_command[**P]( *, @@ -34,6 +41,7 @@ def command[**P]( class ApplicationCommand: qualified_name: str + callback: CommandCallback class SlashCommand(ApplicationCommand): ... class UserCommand(ApplicationCommand): ... @@ -42,6 +50,13 @@ class MessageCommand(ApplicationCommand): ... class SlashCommandGroup(ApplicationCommand): @override def __init__(self, name: str, description: str) -> None: ... + # NOTE: Overloaded because omitting `cls` leaves `T` unsolvable, which resolves to + # `Never` & silently removes every command within a group from type-checking. + @overload + def command[**P]( + self, *, name: str, description: str + ) -> Callable[[Callable[P, Awaitable[None]]], SlashCommand]: ... + @overload def command[**P, T: ApplicationCommand]( - self, cls: type[T] = ..., *, name: str, description: str + self, cls: type[T], *, name: str, description: str ) -> Callable[[Callable[P, Awaitable[None]]], T]: ... diff --git a/stubs/discord/commands/options.pyi b/stubs/discord/commands/options.pyi index 0b08642ba..19a4a308f 100644 --- a/stubs/discord/commands/options.pyi +++ b/stubs/discord/commands/options.pyi @@ -6,6 +6,10 @@ from typing import overload, override from discord.commands.context import AutocompleteContext +type AutocompleteValues = ( + AbstractSet[OptionChoice] | AbstractSet[str] | Sequence[OptionChoice] | Sequence[str] +) + class Option: ... class OptionChoice: @@ -25,14 +29,8 @@ def option[**P, **Q, T, T_context: AutocompleteContext]( | AbstractSet[int] | AbstractSet[float] = ..., parameter_name: str = ..., - autocomplete: Callable[ - [T_context], - Awaitable[AbstractSet[OptionChoice] | AbstractSet[str]], - ] - | Callable[ - [T_context], - Awaitable[AbstractSet[OptionChoice] | AbstractSet[str] | AbstractSet[int]], - ] = ..., + autocomplete: Callable[[T_context], Awaitable[AutocompleteValues]] + | Callable[[T_context], Awaitable[AutocompleteValues | AbstractSet[int]]] = ..., ) -> Callable[[Callable[P, Awaitable[None]]], Callable[Q, Awaitable[None]]]: ... @overload def option[**P, **Q, T_context: AutocompleteContext]( @@ -46,14 +44,8 @@ def option[**P, **Q, T_context: AutocompleteContext]( | AbstractSet[str] | AbstractSet[int] | AbstractSet[float] = ..., - autocomplete: Callable[ - [T_context], - Awaitable[AbstractSet[OptionChoice] | AbstractSet[str]], - ] - | Callable[ - [T_context], - Awaitable[AbstractSet[OptionChoice] | AbstractSet[str] | AbstractSet[int]], - ] = ..., + autocomplete: Callable[[T_context], Awaitable[AutocompleteValues]] + | Callable[[T_context], Awaitable[AutocompleteValues | AbstractSet[int]]] = ..., required: bool = ..., min_length: int = ..., max_length: int = ..., diff --git a/stubs/discord_logging/handler.pyi b/stubs/discord_logging/handler.pyi index d95804406..f303320c5 100644 --- a/stubs/discord_logging/handler.pyi +++ b/stubs/discord_logging/handler.pyi @@ -5,6 +5,9 @@ from collections.abc import Mapping, Sequence from typing import override class DiscordHandler(logging.Handler): + service_name: str + avatar_url: str | None + @override def __init__( self, diff --git a/tests/config/__init__.py b/tests/config/__init__.py new file mode 100644 index 000000000..11f1db1f3 --- /dev/null +++ b/tests/config/__init__.py @@ -0,0 +1,8 @@ +"""Test suite for the config package.""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + +__all__: Sequence[str] = () diff --git a/tests/config/conftest.py b/tests/config/conftest.py new file mode 100644 index 000000000..06c871cc2 --- /dev/null +++ b/tests/config/conftest.py @@ -0,0 +1,99 @@ +"""Shared fixtures & constants for the config package test suite.""" + +import logging +from typing import TYPE_CHECKING + +import pytest + +from config._logging import DISCORD_LOGGER_NAME, LOGGER_NAME + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + from logging import Handler, Logger + from pathlib import Path + from typing import Final + + type ConfigWriter = "Callable[[str], Path]" + + +__all__: Sequence[str] = ( + "CHANGED_EASTER_EGG_PROBABILITY", + "DEFAULT_EASTER_EGG_PROBABILITY", + "MINIMAL_CONFIG", + "VALID_BOT_TOKEN", + "VALID_MAIN_GUILD_ID", + "VALID_WEBHOOK_URL", +) + + +# NOTE: A fabricated value, structured to satisfy the bot-token pattern: +# 24-26 characters, then 6, then 27-38. +VALID_BOT_TOKEN: Final[str] = "MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs" # noqa: S105 + +VALID_MAIN_GUILD_ID: Final[int] = 1234567890123456789 + +VALID_WEBHOOK_URL: Final[str] = "https://discord.com/api/webhooks/123456789/abcdefg" + +DEFAULT_EASTER_EGG_PROBABILITY: Final[float] = 0.01 + +CHANGED_EASTER_EGG_PROBABILITY: Final[float] = 0.5 + +MINIMAL_CONFIG: Final[str] = f"""\ +# A deployment configuration holding only the settings that are required. +discord: + bot-token: {VALID_BOT_TOKEN} + main-guild-id: {VALID_MAIN_GUILD_ID} +""" + + +@pytest.fixture(autouse=True) +def _restore_loggers() -> Iterator[None]: + """ + Restore both loggers to the state they were in before each test. + + Logging is process-wide, so without this any test that applied a configuration + (including every test that reloads one, or runs `/config reload`) would leave its + handlers, level & propagation attached for every test that ran afterwards, making + the results depend upon the order the tests happened to be collected in. + """ + tex_bot_logger: Logger = logging.getLogger(LOGGER_NAME) + discord_logger: Logger = logging.getLogger(DISCORD_LOGGER_NAME) + + ORIGINAL_STATE: Final[Sequence[tuple[Logger, Sequence[Handler], int, bool]]] = tuple( + ( + single_logger, + tuple(single_logger.handlers), + single_logger.level, + single_logger.propagate, + ) + for single_logger in (tex_bot_logger, discord_logger) + ) + + yield + + single_logger: Logger + original_handlers: Sequence[Handler] + original_level: int + original_propagate: bool + for single_logger, original_handlers, original_level, original_propagate in ORIGINAL_STATE: + single_logger.handlers = list(original_handlers) + single_logger.setLevel(original_level) + single_logger.propagate = original_propagate + + +@pytest.fixture() +def write_config(tmp_path: Path) -> ConfigWriter: + """Return a callable writing the given YAML into a configuration file.""" + + def _write_config(raw_yaml: str) -> Path: + config_file_path: Path = tmp_path / "tex-bot-deployment.yaml" + config_file_path.write_text(raw_yaml, encoding="utf-8") + return config_file_path + + return _write_config + + +@pytest.fixture() +def config_file(write_config: ConfigWriter) -> Path: + """Return the path of a configuration file holding only the required settings.""" + return write_config(MINIMAL_CONFIG) diff --git a/tests/config/test_accessor.py b/tests/config/test_accessor.py new file mode 100644 index 000000000..061600636 --- /dev/null +++ b/tests/config/test_accessor.py @@ -0,0 +1,405 @@ +"""Test suite for run-time access to the validated configuration.""" + +import datetime +from typing import TYPE_CHECKING + +import pytest + +from config import ( + SettingsFileNotFoundError, + SettingsNotLoadedError, + SettingsValidationError, +) +from config._accessor import SettingsAccessor + +from .conftest import ( + CHANGED_EASTER_EGG_PROBABILITY, + DEFAULT_EASTER_EGG_PROBABILITY, + MINIMAL_CONFIG, + VALID_BOT_TOKEN, + VALID_WEBHOOK_URL, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, Sequence + from collections.abc import Set as AbstractSet + from pathlib import Path + from typing import Final + + type ConfigWriter = "Callable[[str], Path]" + +__all__: Sequence[str] = () + + +CONFIG_WITH_OPTIONAL_SETTINGS: Final[str] = f"""\ +discord: + bot-token: {VALID_BOT_TOKEN} + main-guild-id: 1234567890123456789 +community-group: + full-name: Computer Science Society + links: {{}} + msl: {{}} +commands: + ping: + easter-egg-probability: 0.01 + strike: + timeout-duration: 24h +""" + + +@pytest.fixture() +def loaded_accessor(config_file: Path) -> SettingsAccessor: + """Return an accessor that has loaded the minimal configuration.""" + settings: SettingsAccessor = SettingsAccessor() + settings.reload(config_file) + return settings + + +class TestLoading: + """Test case for loading configuration into the accessor.""" + + @staticmethod + def test_accessing_settings_before_loading_is_refused() -> None: + """Test that reading a setting before any configuration is loaded is refused.""" + settings: SettingsAccessor = SettingsAccessor() + + assert not settings.is_loaded + + with pytest.raises(SettingsNotLoadedError): + _ = settings.discord.main_guild_id + + @staticmethod + def test_nothing_loaded_has_not_been_changed_underneath() -> None: + """ + Test that an accessor holding no configuration reports no change to the file. + + There is nothing loaded for a file to have diverged from, which is the state + TeX-Bot is in while it is still starting up. + """ + assert not SettingsAccessor().file_has_changed() + + @staticmethod + @pytest.mark.parametrize("edited_contents", ("discord: {unclosed\n", "", None)) + def test_an_unreadable_file_has_been_changed_underneath( + config_file: Path, edited_contents: str | None + ) -> None: + """ + Test that a file which can no longer be read at all is reported as changed. + + A file edited into a state that cannot be parsed certainly no longer holds the + configuration loaded from it. Saying so (rather than raising) is what allows + `/config get` to explain the problem instead of failing without a response. + """ + settings: SettingsAccessor = SettingsAccessor() + settings.reload(config_file) + + if edited_contents is None: + config_file.unlink() + else: + config_file.write_text(edited_contents, encoding="utf-8") + + assert settings.file_has_changed() + + @staticmethod + def test_loading_makes_settings_available(config_file: Path) -> None: + """Test that settings can be read once a configuration has been loaded.""" + settings: SettingsAccessor = SettingsAccessor() + + settings.reload(config_file) + + assert settings.is_loaded + assert settings.discord.main_guild_id == 1234567890123456789 + assert settings.file_path == config_file + + @staticmethod + def test_defaults_are_available_for_omitted_settings( + loaded_accessor: SettingsAccessor, + ) -> None: + """Test that a setting left out of the file still has its default value.""" + assert loaded_accessor.commands.strike.timeout_duration == datetime.timedelta(hours=24) + assert loaded_accessor.community_group.membership_dependent_roles == () + + @staticmethod + def test_settings_are_typed(loaded_accessor: SettingsAccessor) -> None: + """Test that settings are exposed as the types they represent.""" + assert isinstance(loaded_accessor.discord.main_guild_id, int) + assert isinstance(loaded_accessor.commands.strike.timeout_duration, datetime.timedelta) + assert isinstance(loaded_accessor.commands.stats.lookback_days, float) + + +class TestChangeDetection: + """Test case for reporting which settings changed upon each reload.""" + + @staticmethod + def test_first_load_reports_every_setting_as_changed(config_file: Path) -> None: + """Test that loading a configuration for the first time reports all of it.""" + settings: SettingsAccessor = SettingsAccessor() + + assert len(settings.reload(config_file)) > 1 + + @staticmethod + def test_reloading_an_unchanged_file_reports_nothing( + loaded_accessor: SettingsAccessor, config_file: Path + ) -> None: + """Test that reloading an untouched configuration reports no changes.""" + assert loaded_accessor.reload(config_file) == set() + + @staticmethod + def test_a_single_change_is_reported_alone( + write_config: ConfigWriter, + ) -> None: + """Test that changing one setting reports only that setting.""" + settings: SettingsAccessor = SettingsAccessor() + settings.reload(write_config(CONFIG_WITH_OPTIONAL_SETTINGS)) + + CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload( + write_config( + CONFIG_WITH_OPTIONAL_SETTINGS.replace( + "easter-egg-probability: 0.01", "easter-egg-probability: 0.5" + ) + ) + ) + + assert {"commands:ping:easter-egg-probability"} == CHANGED_SETTINGS + assert settings.commands.ping.easter_egg_probability == CHANGED_EASTER_EGG_PROBABILITY + + @staticmethod + def test_an_appearing_section_reports_the_settings_within_it( + write_config: ConfigWriter, + ) -> None: + """Test that adding an optional section reports the settings it introduces.""" + settings: SettingsAccessor = SettingsAccessor() + settings.reload(write_config(MINIMAL_CONFIG)) + + CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload( + write_config( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + ) + ) + + assert "logging:discord-channel:webhook-url" in CHANGED_SETTINGS + assert settings.logging.discord_channel is not None + + @staticmethod + def test_a_disappearing_section_reports_the_settings_it_removed( + write_config: ConfigWriter, + ) -> None: + """ + Test that removing an optional section reports the settings it took with it. + + A section is expanded into the settings within it whether it is present or not, + holding nothing where it is absent, so that removing it is reported as the + individual settings it unset rather than as the section itself. Reporting the + section would name something that is not a setting at all, & that `/config get` + would therefore refuse to show. + """ + settings: SettingsAccessor = SettingsAccessor() + settings.reload( + write_config( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + ) + ) + + CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload( + write_config(MINIMAL_CONFIG) + ) + + assert "logging:discord-channel:webhook-url" in CHANGED_SETTINGS + assert "logging:discord-channel:log-level" in CHANGED_SETTINGS + # NOTE: The section itself is never reported: it is not a setting that could be + # looked up, so naming it would be naming something `/config get` would refuse. + assert "logging:discord-channel" not in CHANGED_SETTINGS + assert settings.logging.discord_channel is None + + @staticmethod + def test_a_changed_secret_is_detected(write_config: ConfigWriter) -> None: + """ + Test that replacing a secret value is reported as a change. + + A secret is held as an opaque object rather than as plain text, so a comparison + that fell back to identity would report every token as unchanged & leave the + committee member who rotated it with no warning that a restart is needed. + """ + settings: SettingsAccessor = SettingsAccessor() + settings.reload(write_config(MINIMAL_CONFIG)) + + assert settings.reload(write_config(MINIMAL_CONFIG)) == set() + + CHANGED_SETTINGS: Final[AbstractSet[str]] = settings.reload( + write_config( + MINIMAL_CONFIG.replace(VALID_BOT_TOKEN, f"{VALID_BOT_TOKEN[:-4]}wxyz") + ) + ) + + assert {"discord:bot-token"} == CHANGED_SETTINGS + + +class TestFailedReloads: + """Test case for what happens when a configuration cannot be loaded.""" + + @staticmethod + def test_invalid_configuration_is_rejected( + loaded_accessor: SettingsAccessor, write_config: ConfigWriter + ) -> None: + """Test that a configuration failing validation is refused.""" + with pytest.raises(SettingsValidationError): + loaded_accessor.reload( + write_config( + f"{MINIMAL_CONFIG}commands:\n ping:\n easter-egg-probability: 9.9\n" + ) + ) + + @staticmethod + def test_invalid_configuration_leaves_the_previous_one_running( + loaded_accessor: SettingsAccessor, write_config: ConfigWriter + ) -> None: + """ + Test that a rejected configuration does not disturb the one already loaded. + + A mistake within the configuration file must not be able to take down a bot + that is running perfectly well. + """ + PREVIOUS_MAIN_GUILD_ID: Final[int] = loaded_accessor.discord.main_guild_id + + with pytest.raises(SettingsValidationError): + loaded_accessor.reload( + write_config( + "discord:\n" + " bot-token: not-a-real-token\n" + " main-guild-id: 9876543210987654321\n" + "community-group:\n" + " links: {}\n" + " msl: {}\n" + ) + ) + + assert loaded_accessor.is_loaded + assert loaded_accessor.discord.main_guild_id == PREVIOUS_MAIN_GUILD_ID + + @staticmethod + def test_a_missing_file_leaves_the_previous_configuration_running( + loaded_accessor: SettingsAccessor, tmp_path: Path + ) -> None: + """Test that failing to find the file does not disturb the loaded configuration.""" + PREVIOUS_MAIN_GUILD_ID: Final[int] = loaded_accessor.discord.main_guild_id + + with pytest.raises(SettingsFileNotFoundError, match="No configuration file"): + loaded_accessor.reload(tmp_path / "vanished.yaml") + + assert loaded_accessor.discord.main_guild_id == PREVIOUS_MAIN_GUILD_ID + + @staticmethod + def test_validation_errors_name_the_line_responsible( + loaded_accessor: SettingsAccessor, write_config: ConfigWriter + ) -> None: + """Test that a rejected configuration explains where the mistake is.""" + with pytest.raises(SettingsValidationError, match=r"tex-bot-deployment\.yaml:"): + loaded_accessor.reload( + write_config( + f"{MINIMAL_CONFIG}logging:\n console:\n log-level: NONSENSE\n" + ) + ) + + +class TestSnapshotIsolation: + """Test case for the immutability of a loaded configuration.""" + + @staticmethod + def test_settings_cannot_be_modified(loaded_accessor: SettingsAccessor) -> None: + """Test that a loaded setting cannot be overwritten in place.""" + with pytest.raises(ValueError, match="frozen"): + loaded_accessor.discord.main_guild_id = 1 # type: ignore[misc] + + @staticmethod + def test_a_previously_read_section_is_unaffected_by_a_reload( + write_config: ConfigWriter, + ) -> None: + """ + Test that a section read before a reload keeps the values it was read with. + + Replacing the whole snapshot, rather than mutating settings individually, is + what stops a caller part-way through its work from seeing a mixture of the old + and new configurations. + """ + settings: SettingsAccessor = SettingsAccessor() + settings.reload(write_config(CONFIG_WITH_OPTIONAL_SETTINGS)) + + commands_before_reload = settings.commands + + settings.reload( + write_config( + CONFIG_WITH_OPTIONAL_SETTINGS.replace( + "easter-egg-probability: 0.01", "easter-egg-probability: 0.5" + ) + ) + ) + + assert ( + commands_before_reload.ping.easter_egg_probability + == DEFAULT_EASTER_EGG_PROBABILITY + ) + assert settings.commands.ping.easter_egg_probability == CHANGED_EASTER_EGG_PROBABILITY + + +class TestFlatMapping: + """Test case for listing every setting by name.""" + + @staticmethod + def test_settings_are_listed_by_key_path(loaded_accessor: SettingsAccessor) -> None: + """Test that every setting is available under its colon-separated key path.""" + FLAT_SETTINGS: Final[Mapping[str, object]] = loaded_accessor.as_flat_mapping() + + assert FLAT_SETTINGS["discord:main-guild-id"] == 1234567890123456789 + assert ( + FLAT_SETTINGS["commands:ping:easter-egg-probability"] + == DEFAULT_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_secrets_are_not_revealed_by_listing_settings( + loaded_accessor: SettingsAccessor, + ) -> None: + """Test that listing every setting does not expose a secret value.""" + assert VALID_BOT_TOKEN not in repr(loaded_accessor.as_flat_mapping()) + + @staticmethod + def test_listing_settings_before_loading_is_refused() -> None: + """Test that listing settings before any are loaded is refused.""" + with pytest.raises(SettingsNotLoadedError): + SettingsAccessor().as_flat_mapping() + + +class TestSectionAccessors: + """Test case for reaching each section of the configuration.""" + + @staticmethod + def test_every_section_is_reachable(loaded_accessor: SettingsAccessor) -> None: + """Test that each top-level section of the configuration can be read.""" + assert loaded_accessor.logging.console.log_level == "INFO" + assert loaded_accessor.discord.main_guild_id == 1234567890123456789 + assert loaded_accessor.community_group.links.purchase_membership is None + assert ( + loaded_accessor.commands.ping.easter_egg_probability + == DEFAULT_EASTER_EGG_PROBABILITY + ) + assert loaded_accessor.reminders.send_get_roles_reminders.enabled is True + assert loaded_accessor.auto_add_committee_to_threads is True + + @staticmethod + def test_the_underlying_document_is_reachable( + loaded_accessor: SettingsAccessor, config_file: Path + ) -> None: + """ + Test that the document the configuration was parsed from is available. + + Rewriting an individual setting needs the document, rather than the validated + values taken from it, so that the order & quoting of the file are retained. + """ + assert loaded_accessor.document.file_path == config_file + assert "discord" in loaded_accessor.document.raw diff --git a/tests/config/test_command.py b/tests/config/test_command.py new file mode 100644 index 000000000..ce9801d68 --- /dev/null +++ b/tests/config/test_command.py @@ -0,0 +1,440 @@ +"""Test suite for the "/config" command group.""" + +import asyncio +from typing import TYPE_CHECKING, cast, override + +import pytest + +import config +from config._accessor import SettingsAccessor +from config._document import SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME + +from .conftest import MINIMAL_CONFIG, VALID_BOT_TOKEN, VALID_WEBHOOK_URL + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + from pathlib import Path + from typing import Final + + from cogs.config import ConfigCommandsCog + from utils import TeXBot + + type ConfigReloadRunner = "Callable[[str | None], Sequence[str]]" + +__all__: Sequence[str] = () + + +class _RecordingApplicationContext: + """A stand-in for the Discord context that a slash command is invoked with.""" + + @override + def __init__(self) -> None: + """Initialise a context that has been responded to with nothing so far.""" + self.responses: list[str] = [] + + async def defer(self, *, ephemeral: bool = False) -> None: + """Record that the command asked for more time to respond.""" + + async def respond(self, message: str, *, ephemeral: bool = False) -> None: # noqa: ARG002 + """Record a response sent back to the committee member that ran the command.""" + self.responses.append(message) + + +@pytest.fixture(scope="module") +def config_commands_cog( + tmp_path_factory: pytest.TempPathFactory, +) -> Iterator[type[ConfigCommandsCog]]: + """ + Return the cog class defining the `/config` command group. + + Importing any cog loads every other one alongside it, several of which read the + configuration as they are imported, so a valid configuration must already be loaded + before the import can succeed at all. + """ + with pytest.MonkeyPatch.context() as module_monkeypatch: + CONFIG_FILE_PATH: Final[Path] = ( + tmp_path_factory.mktemp("config-command") / "tex-bot-deployment.yaml" + ) + CONFIG_FILE_PATH.write_text(MINIMAL_CONFIG, encoding="utf-8") + module_monkeypatch.setenv( + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(CONFIG_FILE_PATH) + ) + config.reload_settings() + + from cogs.config import ConfigCommandsCog # noqa: PLC0415 + + yield ConfigCommandsCog + + +@pytest.fixture() +def run_config_reload( + config_commands_cog: type[ConfigCommandsCog], + write_config: Callable[[str], Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> ConfigReloadRunner: + """ + Return a callable running the `/config reload` command against the given file. + + Passing `None` in place of a configuration runs the command with no configuration + file present at all. Each test begins from an accessor holding no configuration, so + that what the command reports does not depend upon what the previous test loaded. + """ + monkeypatch.setattr(config, "settings", SettingsAccessor()) + + # NOTE: The reload command never reaches for the running bot, so it does not need + # a connection to Discord in order to be exercised. + cog: ConfigCommandsCog = config_commands_cog(bot=cast("TeXBot", None)) + + def _run_config_reload(raw_yaml: str | None) -> Sequence[str]: + monkeypatch.setenv( + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, + str( + write_config(raw_yaml) + if raw_yaml is not None + else tmp_path / "no-such-file.yaml" + ), + ) + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run(config_commands_cog.reload.callback(cog, context)) + + return context.responses + + return _run_config_reload + + +class TestSuccessfulReloads: + """Test case for reloading a configuration that can be applied.""" + + @staticmethod + def test_the_settings_that_changed_are_reported( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that a successful reload names the settings it applied.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + f"{MINIMAL_CONFIG}logging:\n console:\n log-level: DEBUG\n" + ) + + assert len(RESPONSES) == 1 + assert "Reloaded the configuration file" in RESPONSES[0] + assert "`logging:console:log-level`" in RESPONSES[0] + + @staticmethod + def test_an_unchanged_configuration_is_reported( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that reloading without editing the file says so, rather than nothing.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload(MINIMAL_CONFIG) + + assert len(RESPONSES) == 1 + assert "has not changed" in RESPONSES[0] + + @staticmethod + def test_a_very_long_list_of_changes_is_truncated( + run_config_reload: ConfigReloadRunner, + ) -> None: + """ + Test that reporting a great many changes does not produce an endless message. + + The very first reload reports every setting as changed, which is far more than + can be listed within a single Discord message. + """ + from cogs.config import MAXIMUM_LISTED_SETTINGS # noqa: PLC0415 + + RESPONSES: Final[Sequence[str]] = run_config_reload(MINIMAL_CONFIG) + + CHANGED_SETTINGS_LIST: Final[str] = RESPONSES[0].split(":warning:")[0] + + assert "- _...and " in CHANGED_SETTINGS_LIST + assert CHANGED_SETTINGS_LIST.count("\n- `") == MAXIMUM_LISTED_SETTINGS + + +class TestRestartRequiredWarning: + """Test case for warning that a change cannot take effect until a restart.""" + + @staticmethod + def test_a_setting_fixed_at_start_up_is_called_out( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that changing a setting which needs a restart says so explicitly.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + MINIMAL_CONFIG.replace("1234567890123456789", "9876543210987654321") + ) + + assert "must be restarted" in RESPONSES[0] + assert "`discord:main-guild-id`" in RESPONSES[0] + assert "Every other change" not in RESPONSES[0] + + @staticmethod + def test_other_changes_are_reported_as_applied_alongside_restart_settings( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that a reload also changing other settings says those were applied.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + MINIMAL_CONFIG.replace("1234567890123456789", "9876543210987654321") + + "logging:\n console:\n log-level: DEBUG\n" + ) + + assert "must be restarted" in RESPONSES[0] + assert "Every other change above has already been applied." in RESPONSES[0] + + @staticmethod + def test_a_setting_applied_immediately_is_not_called_out( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that a change taking effect at once does not ask for a restart.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + f"{MINIMAL_CONFIG}logging:\n console:\n log-level: DEBUG\n" + ) + + assert "must be restarted" not in RESPONSES[0] + assert "Every other change" not in RESPONSES[0] + + +class TestSettingsAwaitingRestart: + """Test case for showing a setting whose new value is waiting for a restart.""" + + @staticmethod + def test_setting_a_value_reports_the_new_value( + run_config_reload: ConfigReloadRunner, + config_commands_cog: type[ConfigCommandsCog], + ) -> None: + """ + Test that changing a setting which needs a restart repeats back its new value. + + TeX-Bot keeps running with the old value until it restarts, so repeating back + the value it is running would look as though the change had been ignored. + """ + run_config_reload(MINIMAL_CONFIG) + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run( + config_commands_cog.set.callback( + config_commands_cog(bot=cast("TeXBot", None)), + context, + "discord:main-guild-id", + "9876543210987654321", + ) + ) + + assert "to `9876543210987654321`" in context.responses[0] + assert "must be restarted" in context.responses[0] + + @staticmethod + def test_the_value_awaiting_a_restart_is_shown( + run_config_reload: ConfigReloadRunner, + config_commands_cog: type[ConfigCommandsCog], + ) -> None: + """Test that viewing a setting shows both the running value & the one to come.""" + run_config_reload(MINIMAL_CONFIG) + run_config_reload(MINIMAL_CONFIG.replace("1234567890123456789", "9876543210987654321")) + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run( + config_commands_cog.get.callback( + config_commands_cog(bot=cast("TeXBot", None)), + context, + "discord:main-guild-id", + ) + ) + + assert "`1234567890123456789`" in context.responses[0] + assert ( + "The configuration file changes this to `9876543210987654321`, " + "which will not take effect until TeX-Bot is restarted." + ) in context.responses[0] + + @staticmethod + def test_a_value_awaiting_a_restart_is_not_mistaken_for_an_edit_by_hand( + run_config_reload: ConfigReloadRunner, + config_commands_cog: type[ConfigCommandsCog], + write_config: Callable[[str], Path], + ) -> None: + """ + Test that a reload is not suggested to apply a value only a restart can apply. + + A different setting is edited by hand, so the file no longer matches what was + loaded, but the setting being viewed was not touched by that edit. + """ + CHANGED_CONFIG: Final[str] = MINIMAL_CONFIG.replace( + "1234567890123456789", "9876543210987654321" + ) + run_config_reload(MINIMAL_CONFIG) + run_config_reload(CHANGED_CONFIG) + write_config(f"{CHANGED_CONFIG}logging:\n console:\n log-level: DEBUG\n") + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run( + config_commands_cog.get.callback( + config_commands_cog(bot=cast("TeXBot", None)), + context, + "discord:main-guild-id", + ) + ) + + assert "though not this setting" in context.responses[0] + assert "will not take effect until TeX-Bot is restarted" in context.responses[0] + + @staticmethod + def test_a_start_up_value_is_not_called_the_default( + run_config_reload: ConfigReloadRunner, + config_commands_cog: type[ConfigCommandsCog], + ) -> None: + """Test that removing a setting needing a restart does not relabel its old value.""" + run_config_reload(f"{MINIMAL_CONFIG}community-group:\n short-name: CSS\n") + run_config_reload(MINIMAL_CONFIG) + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run( + config_commands_cog.get.callback( + config_commands_cog(bot=cast("TeXBot", None)), + context, + "community-group:short-name", + ) + ) + + assert "`CSS`" in context.responses[0] + assert "(default" not in context.responses[0] + assert "The configuration file changes this to" in context.responses[0] + + +class TestRemovingASettingAnOptionalSectionNeeds: + """Test case for removing a setting that a whole optional section depends upon.""" + + @staticmethod + def test_the_removed_section_is_reported( + run_config_reload: ConfigReloadRunner, + config_commands_cog: type[ConfigCommandsCog], + ) -> None: + """Test that removing a webhook URL says the whole log-channel section went too.""" + run_config_reload( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + f" log-level: ERROR\n" + ) + + context: _RecordingApplicationContext = _RecordingApplicationContext() + asyncio.run( + config_commands_cog.unset.callback( + config_commands_cog(bot=cast("TeXBot", None)), + context, + "logging:discord-channel:webhook-url", + ) + ) + + assert ":white_check_mark: Removed" in context.responses[0] + assert "The whole of **`logging:discord-channel`** was removed" in context.responses[0] + + +class TestRejectedReloads: + """Test case for reporting a configuration that could not be loaded.""" + + @staticmethod + def test_invalid_settings_are_reported_without_being_applied( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that a configuration failing validation is refused & explained.""" + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + f"{MINIMAL_CONFIG}logging:\n console:\n log-level: NONSENSE\n" + ) + + assert "was **not** loaded" in RESPONSES[0] + assert "invalid settings" in RESPONSES[0] + assert config.settings.logging.console.log_level == "INFO" + + @staticmethod + def test_a_rejected_secret_is_not_echoed_back( + run_config_reload: ConfigReloadRunner, + ) -> None: + """Test that an invalid token is not quoted back into a Discord channel.""" + INVALID_TOKEN: Final[str] = "NOT-A-REAL-TOKEN-BUT-STILL-SECRET" # noqa: S105 + + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + MINIMAL_CONFIG.replace(VALID_BOT_TOKEN, INVALID_TOKEN) + ) + + assert "was **not** loaded" in RESPONSES[0] + assert INVALID_TOKEN not in RESPONSES[0] + + @staticmethod + def test_a_configuration_holding_many_errors_still_fits_within_one_message( + run_config_reload: ConfigReloadRunner, + ) -> None: + """ + Test that a great many validation failures are shortened rather than refused. + + Discord rejects a message beyond its length limit in its entirety, so a response + that was not shortened would leave the committee member with no explanation at + all, at exactly the moment one is most needed. + """ + from cogs.config import MAXIMUM_MESSAGE_LENGTH, TRUNCATION_NOTICE # noqa: PLC0415 + + UNKNOWN_SETTINGS: Final[str] = "".join( + f"unknown-setting-{unknown_setting_number}: {unknown_setting_number}\n" + for unknown_setting_number in range(100) + ) + + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload( + f"{MINIMAL_CONFIG}{UNKNOWN_SETTINGS}" + ) + + assert "was **not** loaded" in RESPONSES[0] + assert len(RESPONSES[0]) <= MAXIMUM_MESSAGE_LENGTH + assert RESPONSES[0].endswith("```") + assert TRUNCATION_NOTICE in RESPONSES[0] + + @staticmethod + def test_a_missing_configuration_file_is_reported( + run_config_reload: ConfigReloadRunner, + ) -> None: + """ + Test that running the command with no configuration file is reported clearly. + + Failing to find the file does not raise an operating-system error, so catching + one is not enough to keep this from surfacing as an unhandled exception. + """ + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload(None) + + assert len(RESPONSES) == 1 + assert "could not be read" in RESPONSES[0] + + @staticmethod + @pytest.mark.parametrize( + "raw_yaml", ("discord:\n bot-token: [unclosed\n", "", "just-a-string\n") + ) + def test_an_unreadable_configuration_file_is_reported( + run_config_reload: ConfigReloadRunner, raw_yaml: str + ) -> None: + """ + Test that a file that cannot be parsed at all is reported clearly. + + Nor does failing to parse the file raise an operating-system error, so this too + would otherwise surface as an unhandled exception rather than as an explanation. + """ + run_config_reload(MINIMAL_CONFIG) + + RESPONSES: Final[Sequence[str]] = run_config_reload(raw_yaml) + + assert len(RESPONSES) == 1 + assert "could not be read" in RESPONSES[0] diff --git a/tests/config/test_document.py b/tests/config/test_document.py new file mode 100644 index 000000000..f21d4b230 --- /dev/null +++ b/tests/config/test_document.py @@ -0,0 +1,734 @@ +"""Test suite for reading, writing & error-reporting of the configuration file.""" + +import os +import stat +from typing import TYPE_CHECKING +from unittest import mock + +import pytest +from pydantic import ValidationError + +from config import ( + InvalidSettingsFileError, + SettingsDocument, + SettingsFileNotFoundError, + get_settings_file_path, +) +from config._document import ( + PROJECT_ROOT, + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, +) +from config._schema import SettingsSchema + +from .conftest import MINIMAL_CONFIG, VALID_BOT_TOKEN + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from pathlib import Path + from typing import Final + + type ConfigWriter = "Callable[[str], Path]" + +__all__: Sequence[str] = () + + +COMMENTED_CONFIG: Final[str] = f"""\ +# A leading comment about the whole file. + +discord: + # A comment about the bot token. + bot-token: {VALID_BOT_TOKEN} + main-guild-id: 1234567890123456789 # A trailing comment. + +community-group: + full-name: Computer Science Society # Another trailing comment. + links: {{}} + msl: {{}} +""" + + +class TestLoading: + """Test case for parsing the configuration file.""" + + @staticmethod + def test_valid_file_is_loaded(config_file: Path) -> None: + """Test that a valid configuration file is parsed.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + assert document.file_path == config_file + assert document.raw["discord"]["main-guild-id"] == 1234567890123456789 + + @staticmethod + def test_missing_file_is_reported(tmp_path: Path) -> None: + """Test that a configuration file that does not exist is reported clearly.""" + with pytest.raises(SettingsFileNotFoundError): + SettingsDocument.load(tmp_path / "does-not-exist.yaml") + + @staticmethod + def test_malformed_yaml_is_reported(write_config: ConfigWriter) -> None: + """Test that a file that is not valid YAML is reported clearly.""" + with pytest.raises(InvalidSettingsFileError, match="not a valid YAML file"): + SettingsDocument.load(write_config("discord:\n bot-token: [unclosed\n")) + + @staticmethod + def test_a_file_that_is_not_utf_8_is_reported(config_file: Path) -> None: + """ + Test that a file saved in a different text encoding is reported clearly. + + A file saved as Latin-1 holding an accented character cannot be read as UTF-8, + & would otherwise fail with an error that no caller expects. + """ + config_file.write_bytes( + f"{MINIMAL_CONFIG}community-group:\n full-name: Société\n".encode("latin-1") + ) + + with pytest.raises(InvalidSettingsFileError, match="must be saved as UTF-8"): + SettingsDocument.load(config_file) + + @staticmethod + def test_empty_file_is_reported(write_config: ConfigWriter) -> None: + """Test that an empty configuration file is reported clearly.""" + with pytest.raises(InvalidSettingsFileError, match="is empty"): + SettingsDocument.load(write_config("")) + + @staticmethod + @pytest.mark.parametrize("raw_yaml", ("just-a-string\n", "- one\n- two\n", "42\n")) + def test_file_without_a_top_level_mapping_is_reported( + write_config: ConfigWriter, raw_yaml: str + ) -> None: + """Test that a file not holding a mapping of settings is reported clearly.""" + with pytest.raises(InvalidSettingsFileError, match="must contain a mapping"): + SettingsDocument.load(write_config(raw_yaml)) + + +class TestRoundTripping: + """Test case for writing back the settings of a hand-written configuration file.""" + + @staticmethod + def test_unmodified_file_without_comments_is_written_back_unchanged( + write_config: ConfigWriter, + ) -> None: + """Test that loading & writing back a file holding no comments leaves it as it was.""" + UNCOMMENTED_CONFIG: Final[str] = ( + f"discord:\n" + f" bot-token: {VALID_BOT_TOKEN}\n" + f" main-guild-id: 1234567890123456789\n" + f"community-group:\n" + f" full-name: 'Computer Science Society'\n" + ) + document: SettingsDocument = SettingsDocument.load(write_config(UNCOMMENTED_CONFIG)) + + assert document.dump() == UNCOMMENTED_CONFIG + + @staticmethod + def test_comments_are_not_written_back(write_config: ConfigWriter) -> None: + """ + Test that rewriting a file leaves out every comment, but keeps every setting. + + A comment is attached to whichever setting happens to precede it, so once a + setting is added or removed, keeping it would leave it describing the wrong + setting, or written out at an indentation that is no longer valid YAML. + """ + config_file_path: Path = write_config(COMMENTED_CONFIG) + document: SettingsDocument = SettingsDocument.load(config_file_path) + + document.raw["community-group"]["full-name"] = "CompSoc" + document.write() + + NEW_FILE_CONTENTS: Final[str] = config_file_path.read_text(encoding="utf-8") + + assert "CompSoc" in NEW_FILE_CONTENTS + assert "#" not in NEW_FILE_CONTENTS + assert SettingsDocument.load(config_file_path).raw == document.raw + + @staticmethod + def test_emptying_a_section_beneath_a_comment_leaves_a_loadable_file( + write_config: ConfigWriter, + ) -> None: + """ + Test that removing the only setting of a section, beneath a comment, is written. + + Writing the comment back would place it at an indentation that is not valid YAML, + leaving a file that TeX-Bot could not start from. + """ + config_file_path: Path = write_config( + f"{MINIMAL_CONFIG}" + "commands:\n" + " ping:\n" + " # How often the easter egg appears.\n" + " easter-egg-probability: 0.5\n" + ) + document: SettingsDocument = SettingsDocument.load(config_file_path) + document.unset_value(("commands", "ping", "easter-egg-probability")) + + document.write() + + assert SettingsDocument.load(config_file_path).raw["commands"]["ping"] == {} + + @staticmethod + def test_a_long_value_is_not_re_wrapped(write_config: ConfigWriter) -> None: + """ + Test that writing a file back does not fold its long values onto extra lines. + + A YAML writer wraps at its configured line width by default, which would rewrite + untouched sections of the file & bury the one setting that actually changed + within a diff full of spurious changes. + """ + LONG_VALUE: Final[str] = " ".join(["a very long channel name"] * 12) + + config_file_path: Path = write_config( + f"{MINIMAL_CONFIG}commands:\n" + f" strike:\n" + f" reported-message-destination-channel: {LONG_VALUE}\n" + ) + document: SettingsDocument = SettingsDocument.load(config_file_path) + + document.set_value(["community-group", "full-name"], "CompSoc") + document.write() + + assert ( + f"reported-message-destination-channel: {LONG_VALUE}" + in config_file_path.read_text(encoding="utf-8") + ) + + @staticmethod + def test_written_file_can_be_loaded_again(write_config: ConfigWriter) -> None: + """Test that a rewritten configuration file is still valid.""" + config_file_path: Path = write_config(COMMENTED_CONFIG) + document: SettingsDocument = SettingsDocument.load(config_file_path) + + document.raw["community-group"]["full-name"] = "CompSoc" + document.write() + + assert ( + SettingsSchema.model_validate( + SettingsDocument.load(config_file_path).raw + ).community_group.full_name + == "CompSoc" + ) + + +class TestWriting: + """Test case for persisting the configuration file to disk.""" + + @staticmethod + def _rejecting_replace(*_args: object, **_kwargs: object) -> None: # noqa: CAR150 + """Stand in for a rename that the filesystem refuses.""" + raise OSError(16, "Device or resource busy") + + @staticmethod + @pytest.mark.skipif( + os.name == "nt", reason="Windows does not hold the permission bits being asserted." + ) + @pytest.mark.parametrize("original_permissions", (0o600, 0o640)) + def test_writing_retains_the_permissions_of_the_file_it_replaces( + write_config: ConfigWriter, original_permissions: int + ) -> None: + """ + Test that writing does not widen who may read the configuration file. + + The file holds the bot token & the MSL authentication cookie, so a deployment + that has deliberately restricted who may read it must not have those + restrictions lifted simply because a setting was changed. + """ + config_file_path: Path = write_config(MINIMAL_CONFIG) + config_file_path.chmod(original_permissions) + + document: SettingsDocument = SettingsDocument.load(config_file_path) + document.set_value(["community-group", "full-name"], "CompSoc") + document.write() + + assert stat.S_IMODE(config_file_path.stat().st_mode) == original_permissions + + @staticmethod + def test_no_temporary_file_is_left_behind( + write_config: ConfigWriter, tmp_path: Path + ) -> None: + """Test that writing does not leave its temporary file behind.""" + document: SettingsDocument = SettingsDocument.load(write_config(MINIMAL_CONFIG)) + + document.write() + + assert not [path for path in tmp_path.iterdir() if path.suffix == ".tmp"] + + @staticmethod + def test_write_falls_back_when_the_file_cannot_be_replaced( + write_config: ConfigWriter, tmp_path: Path + ) -> None: + """ + Test that a rejected rename falls back to writing the file directly. + + Replacing an individually mounted file within a container is rejected, so the + fallback is what allows a setting to be saved in that deployment. + """ + config_file_path: Path = write_config(COMMENTED_CONFIG) + document: SettingsDocument = SettingsDocument.load(config_file_path) + document.raw["community-group"]["full-name"] = "FallbackSoc" + + with mock.patch("config._document.os.replace", TestWriting._rejecting_replace): + document.write() + + NEW_FILE_CONTENTS: Final[str] = config_file_path.read_text(encoding="utf-8") + + assert "FallbackSoc" in NEW_FILE_CONTENTS + assert not [path for path in tmp_path.iterdir() if path.suffix == ".tmp"] + + @staticmethod + def test_both_write_paths_produce_identical_output( + write_config: ConfigWriter, tmp_path: Path + ) -> None: + """Test that falling back to writing directly produces the same file.""" + atomically_written_path: Path = write_config(COMMENTED_CONFIG) + atomically_written_document: SettingsDocument = SettingsDocument.load( + atomically_written_path + ) + atomically_written_document.raw["community-group"]["full-name"] = "Same" + atomically_written_document.write() + + directly_written_path: Path = tmp_path / "directly-written.yaml" + directly_written_path.write_text(COMMENTED_CONFIG, encoding="utf-8") + directly_written_document: SettingsDocument = SettingsDocument.load( + directly_written_path + ) + directly_written_document.raw["community-group"]["full-name"] = "Same" + with mock.patch("config._document.os.replace", TestWriting._rejecting_replace): + directly_written_document.write() + + assert atomically_written_path.read_text( + encoding="utf-8" + ) == directly_written_path.read_text(encoding="utf-8") + + @staticmethod + def test_failing_to_write_leaves_the_original_file_intact( + write_config: ConfigWriter, tmp_path: Path + ) -> None: + """Test that a write that fails partway does not damage the existing file.""" + config_file_path: Path = write_config(COMMENTED_CONFIG) + document: SettingsDocument = SettingsDocument.load(config_file_path) + document.raw["community-group"]["full-name"] = "ShouldNotAppear" + + with ( + mock.patch.object( + SettingsDocument, + "_write_privately", + side_effect=OSError(28, "No space left on device"), + ), + pytest.raises(OSError, match="No space left on device"), + ): + document.write() + + assert config_file_path.read_text(encoding="utf-8") == COMMENTED_CONFIG + assert not [path for path in tmp_path.iterdir() if path.suffix == ".tmp"] + + @staticmethod + @pytest.mark.parametrize( + "faulty_file_contents", + ("discord:\n bot-token: [unclosed\n", "discord:\n main-guild-id: 1\n"), + ) + def test_a_document_that_would_not_read_back_is_not_written( + write_config: ConfigWriter, faulty_file_contents: str + ) -> None: + """ + Test that a rewrite producing a file not holding the same settings is refused. + + Both text that is not valid YAML, & text that is valid YAML holding different + settings, would leave behind a file that TeX-Bot could not start from as it was. + """ + config_file_path: Path = write_config(COMMENTED_CONFIG) + document: SettingsDocument = SettingsDocument.load(config_file_path) + document.raw["community-group"]["full-name"] = "ShouldNotAppear" + + with ( + mock.patch.object(SettingsDocument, "dump", return_value=faulty_file_contents), + pytest.raises(InvalidSettingsFileError, match="was not changed"), + ): + document.write() + + assert config_file_path.read_text(encoding="utf-8") == COMMENTED_CONFIG + + +class TestChangingValues: + """Test case for changing the settings held within a document.""" + + @staticmethod + def test_a_setting_is_written_into_an_absent_section(config_file: Path) -> None: + """Test that setting a value creates whichever sections are needed to hold it.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + document.set_value(["reminders", "send-get-roles-reminders", "interval"], "30m") + + assert document.raw["reminders"]["send-get-roles-reminders"]["interval"] == "30m" + + @staticmethod + def test_a_setting_is_written_into_a_section_holding_nothing( + write_config: ConfigWriter, + ) -> None: + """ + Test that a section written with nothing beneath it can still be written into. + + Commenting out every setting within a section leaves it holding null, which is + just as absent as a section that was never written at all. + """ + document: SettingsDocument = SettingsDocument.load( + write_config( + f"{MINIMAL_CONFIG}logging:\n discord-channel:\n # webhook-url: x\n" + ) + ) + + document.set_value(["logging", "discord-channel", "log-level"], "ERROR") + + assert document.raw["logging"]["discord-channel"]["log-level"] == "ERROR" + + @staticmethod + def test_a_change_does_not_reach_the_file_until_it_is_written( + config_file: Path, + ) -> None: + """Test that changing a value alone leaves the file upon disk untouched.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + document.set_value(["community-group", "full-name"], "CompSoc") + + assert config_file.read_text(encoding="utf-8") == MINIMAL_CONFIG + + @staticmethod + def test_a_setting_cannot_be_written_beneath_a_value( + write_config: ConfigWriter, + ) -> None: + """Test that a section which holds a plain value is not overwritten silently.""" + document: SettingsDocument = SettingsDocument.load( + write_config(f"{MINIMAL_CONFIG}commands: not-a-section\n") + ) + + with pytest.raises(InvalidSettingsFileError, match="not a section"): + document.set_value(["commands", "ping", "easter-egg-probability"], 0.5) + + @staticmethod + def test_a_setting_must_be_named(config_file: Path) -> None: + """Test that changing a value requires a setting to change.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + with pytest.raises(ValueError, match="must be named"): + document.set_value([], 0.5) + + @staticmethod + def test_an_absent_setting_is_reported_as_not_removed(config_file: Path) -> None: + """Test that removing a setting the file does not hold reports that it did not.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + assert not document.unset_value(["community-group", "full-name"]) + + @staticmethod + def test_a_document_read_again_is_independent_of_the_one_already_held( + config_file: Path, + ) -> None: + """ + Test that changing a freshly read document leaves an existing one alone. + + A change is applied to the file read afresh & validated before anything is + written, so a change that turns out to be invalid must not be able to reach the + configuration that is currently loaded. + """ + loaded_document: SettingsDocument = SettingsDocument.load(config_file) + + document_being_changed: SettingsDocument = SettingsDocument.load(config_file) + document_being_changed.set_value(["community-group", "full-name"], "CompSoc") + + assert not loaded_document.contains(["community-group", "full-name"]) + assert document_being_changed.contains(["community-group", "full-name"]) + + +class TestErrorReporting: + """Test case for pointing a human at the cause of an invalid configuration.""" + + @staticmethod + def test_errors_name_the_line_that_caused_them(write_config: ConfigWriter) -> None: + """Test that each validation failure is reported against its source line.""" + document: SettingsDocument = SettingsDocument.load( + write_config( + "discord:\n" + " bot-token: not-a-real-token\n" + " main-guild-id: 12\n" + "community-group:\n" + " links: {}\n" + " msl: {}\n" + ) + ) + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate(document.raw) + + FORMATTED_ERROR: Final[str] = document.format_validation_error(validation_error.value) + + assert "tex-bot-deployment.yaml:2" in FORMATTED_ERROR + assert "tex-bot-deployment.yaml:3" in FORMATTED_ERROR + assert "discord:bot-token" in FORMATTED_ERROR + + @staticmethod + def test_errors_never_reveal_the_offending_value( + write_config: ConfigWriter, + ) -> None: + """Test that a rejected value is not quoted back, in case it is a secret.""" + SECRET_LOOKING_TOKEN: Final[str] = "SUPER-SECRET-BUT-INVALID" # noqa: S105 + + document: SettingsDocument = SettingsDocument.load( + write_config( + f"discord:\n" + f" bot-token: {SECRET_LOOKING_TOKEN}\n" + f" main-guild-id: 1234567890123456789\n" + f"community-group:\n" + f" links: {{}}\n" + f" msl: {{}}\n" + ) + ) + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate(document.raw) + + assert SECRET_LOOKING_TOKEN not in document.format_validation_error( + validation_error.value + ) + + @staticmethod + def test_a_missing_setting_is_reported_against_its_nearest_section( + write_config: ConfigWriter, + ) -> None: + """ + Test that an absent setting is still reported against a useful location. + + A setting that is missing entirely has no line of its own, so the closest + section that does exist is reported instead. + """ + document: SettingsDocument = SettingsDocument.load( + write_config( + "discord:\n" + " main-guild-id: 1234567890123456789\n" + "community-group:\n" + " links: {}\n" + " msl: {}\n" + ) + ) + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate(document.raw) + + FORMATTED_ERROR: Final[str] = document.format_validation_error(validation_error.value) + + assert "discord:bot-token" in FORMATTED_ERROR + assert "tex-bot-deployment.yaml:1" in FORMATTED_ERROR + + @staticmethod + def test_line_numbers_of_absent_settings_are_not_invented( + config_file: Path, + ) -> None: + """Test that no line is reported for a key path that cannot be resolved at all.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + assert document.line_number_of(["not-a-section", "not-a-setting"]) is None + + @staticmethod + @pytest.mark.parametrize( + ("key_path", "expected_line_number"), + ( + # NOTE: A key path descending past a value that holds nothing further, one + # naming an entry of a list that does not exist, & one naming an entry of a + # list by something other than its position. + (("discord", "bot-token", "deeper"), 3), + (("commands", "stats", "displayed-roles", 5), 7), + (("commands", "stats", "displayed-roles", "Committee"), 7), + ), + ) + def test_an_unresolvable_key_falls_back_to_the_deepest_line_known( + write_config: ConfigWriter, + key_path: Sequence[str | int], + expected_line_number: int, + ) -> None: + """Test that a key path which cannot be followed reports how far it did reach.""" + document: SettingsDocument = SettingsDocument.load( + write_config( + f"{MINIMAL_CONFIG}" + f"commands:\n" + f" stats:\n" + f" displayed-roles:\n" + f" - Committee\n" + ) + ) + + assert document.line_number_of(key_path) == expected_line_number + + @staticmethod + def test_an_error_within_a_list_is_reported_against_the_entry( + write_config: ConfigWriter, + ) -> None: + """ + Test that a rejected entry of a list is reported against its own line. + + Pydantic identifies such an entry by its position, so the reported key path ends + with a number rather than a name. That position is resolved to the line holding + the entry, rather than to the line the list containing it begins upon, so that a + long list does not point every one of its errors at the same line. + """ + document: SettingsDocument = SettingsDocument.load( + write_config( + f"{MINIMAL_CONFIG}" + f"commands:\n" + f" stats:\n" + f" displayed-roles:\n" + f" - Committee\n" + f" - [a nested list]\n" + ) + ) + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate(document.raw) + + FORMATTED_ERROR: Final[str] = document.format_validation_error(validation_error.value) + + assert "commands:stats:displayed-roles:1" in FORMATTED_ERROR + # NOTE: The line holding the second entry of the list, rather than line 7 that + # `displayed-roles` itself is written upon. + assert "tex-bot-deployment.yaml:9" in FORMATTED_ERROR + + @staticmethod + def test_an_error_with_no_location_is_reported_against_the_whole_file( + config_file: Path, + ) -> None: + """Test that a failure belonging to no particular setting still names the file.""" + document: SettingsDocument = SettingsDocument.load(config_file) + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate("not a mapping of settings at all") + + FORMATTED_ERROR: Final[str] = document.format_validation_error(validation_error.value) + + assert "(whole file)" in FORMATTED_ERROR + assert "tex-bot-deployment.yaml" in FORMATTED_ERROR + + +class TestFileDiscovery: + """Test case for locating the configuration file.""" + + @staticmethod + def test_environment_variable_is_used_when_set( + config_file: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test that the configured environment variable names the file to load.""" + monkeypatch.setenv(SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(config_file)) + + assert get_settings_file_path() == config_file.resolve() + + @staticmethod + def test_missing_file_named_by_the_environment_variable_is_reported( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test that naming a file that does not exist is reported clearly.""" + monkeypatch.setenv( + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(tmp_path / "absent.yaml") + ) + + with pytest.raises(SettingsFileNotFoundError, match="environment variable"): + get_settings_file_path() + + @staticmethod + def test_absent_configuration_is_reported_with_guidance( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test that finding no configuration at all explains how to provide one.""" + monkeypatch.delenv(SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, raising=False) + monkeypatch.setattr("config._document.PROJECT_ROOT", tmp_path) + + with pytest.raises(SettingsFileNotFoundError, match=r"tex-bot-deployment\.yaml"): + get_settings_file_path() + + @staticmethod + def test_default_location_is_used_when_no_environment_variable_is_set( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test that the project root is searched when no location is configured.""" + monkeypatch.delenv(SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, raising=False) + monkeypatch.setattr("config._document.PROJECT_ROOT", tmp_path) + + DEFAULT_CONFIG_FILE_PATH: Final[Path] = tmp_path / "tex-bot-deployment.yaml" + DEFAULT_CONFIG_FILE_PATH.write_text(MINIMAL_CONFIG, encoding="utf-8") + + assert get_settings_file_path() == DEFAULT_CONFIG_FILE_PATH.resolve() + + +class TestExampleConfiguration: + """Test case for the example configuration file shipped alongside TeX-Bot.""" + + @staticmethod + def _example_config_with_required_settings_filled_in() -> str: + """Return the example configuration, with its two required values supplied.""" + RAW_EXAMPLE_CONFIG: Final[str] = ( + PROJECT_ROOT / "tex-bot-deployment.example.yaml" + ).read_text(encoding="utf-8") + + return RAW_EXAMPLE_CONFIG.replace( + 'bot-token: ""', f"bot-token: {VALID_BOT_TOKEN}" + ).replace("main-guild-id: 0", "main-guild-id: 1234567890123456789") + + @staticmethod + def test_the_example_configuration_is_valid(write_config: ConfigWriter) -> None: + """ + Test that the shipped example validates once its required values are filled in. + + Somebody setting TeX-Bot up copies this file, supplies their token & guild ID, + and starts it. Every other setting within it must therefore already be valid as + written, including each one that is only there to show what it would look like. + """ + document: SettingsDocument = SettingsDocument.load( + write_config( + TestExampleConfiguration._example_config_with_required_settings_filled_in() + ) + ) + + SettingsSchema.model_validate(document.raw) + + @staticmethod + def test_the_example_configuration_leaves_optional_settings_absent( + write_config: ConfigWriter, + ) -> None: + """ + Test that the example supplies no placeholder in place of an optional setting. + + A setting that is present must hold a valid value, so a placeholder such as `""` + is rejected rather than treated as the setting having been left unset. + """ + settings: SettingsSchema = SettingsSchema.model_validate( + SettingsDocument.load( + write_config( + TestExampleConfiguration._example_config_with_required_settings_filled_in() + ) + ).raw + ) + + assert settings.community_group.full_name is None + assert settings.community_group.links.purchase_membership is None + assert settings.community_group.msl.organisation_id is None + assert settings.community_group.msl.auth_cookie is None + + +def test_temporary_file_is_written_alongside_its_destination(config_file: Path) -> None: + """ + Test that the temporary file used while writing is created beside the destination. + + Renaming is only atomic within a single filesystem, which writing alongside the + destination guarantees. + """ + document: SettingsDocument = SettingsDocument.load(config_file) + + observed_temporary_paths: list[str] = [] + real_replace = os.replace + + def _recording_replace(src: object, dst: object) -> None: + observed_temporary_paths.append(str(src)) + real_replace(src, dst) # type: ignore[arg-type] + + with mock.patch("config._document.os.replace", _recording_replace): + document.write() + + assert len(observed_temporary_paths) == 1 + assert ( + os.path.dirname(observed_temporary_paths[0]) # noqa: PTH120 + == str(config_file.parent) + ) diff --git a/tests/config/test_editor.py b/tests/config/test_editor.py new file mode 100644 index 000000000..c60573317 --- /dev/null +++ b/tests/config/test_editor.py @@ -0,0 +1,997 @@ +"""Test suite for changing individual settings within the configuration file.""" + +import datetime +from typing import TYPE_CHECKING + +import pytest + +import config +from config import ( + SettingsFileChangedError, + SettingsValidationError, + UnknownSettingError, +) +from config._accessor import SettingsAccessor +from config._document import SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, SettingsDocument +from config._editor import ( + format_setting_value, + parse_setting_value, + validated_document_with_setting_set, +) + +from .conftest import ( + CHANGED_EASTER_EGG_PROBABILITY, + DEFAULT_EASTER_EGG_PROBABILITY, + MINIMAL_CONFIG, + VALID_BOT_TOKEN, + VALID_WEBHOOK_URL, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from pathlib import Path + from typing import Final + + from config import ConfigReloadResult + + type ConfigWriter = "Callable[[str], Path]" + +__all__: Sequence[str] = () + + +COMMENTED_CONFIG: Final[str] = f"""\ +# A leading comment about the whole file. +discord: + # A comment about the bot token. + bot-token: {VALID_BOT_TOKEN} + main-guild-id: 1234567890123456789 +community-group: + full-name: Computer Science Society + links: {{}} + msl: {{}} +commands: + ping: + easter-egg-probability: 0.01 +""" + + +@pytest.fixture() +def configured( + write_config: ConfigWriter, monkeypatch: pytest.MonkeyPatch +) -> Callable[[str], Path]: + """ + Return a callable writing the given configuration & loading it. + + Changing a setting reads & rewrites whichever file the `TEX_BOT_CONFIG_PATH` + environment variable names, so it is pointed at a temporary file for each test. + """ + monkeypatch.setattr(config, "settings", SettingsAccessor()) + + def _configure(raw_yaml: str) -> Path: + CONFIG_FILE_PATH: Final[Path] = write_config(raw_yaml) + monkeypatch.setenv(SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(CONFIG_FILE_PATH)) + config.reload_settings() + return CONFIG_FILE_PATH + + return _configure + + +class TestParsingValues: + """Test case for reading the value that a committee member typed.""" + + @staticmethod + @pytest.mark.parametrize( + ("raw_value", "expected_value"), + ( + ("true", True), + ("false", False), + ("0.5", 0.5), + ("30", 30), + ("1h30m", "1h30m"), + ("DM", "DM"), + ("[Committee, Member]", ["Committee", "Member"]), + ), + ) + def test_a_value_is_read_as_it_would_be_written( + raw_value: str, expected_value: object + ) -> None: + """Test that a value is read exactly as the same text within the file would be.""" + assert ( + parse_setting_value("commands:strike:timeout-duration", raw_value) + == expected_value + ) + + @staticmethod + @pytest.mark.parametrize( + "setting_name", + # NOTE: One setting declared to hold text & one that is not, because each is + # read by a separate path through the parser. + ("community-group:full-name", "commands:strike:timeout-duration"), + ) + def test_a_value_holding_a_colon_is_kept_as_text(setting_name: str) -> None: + """ + Test that text containing a colon is not read as a section of its own. + + `Computer Science: Society` is a perfectly ordinary name, but is also how a + mapping of one key to one value is written. + """ + assert ( + parse_setting_value(setting_name, "Computer Science: Society") + == "Computer Science: Society" + ) + + @staticmethod + @pytest.mark.parametrize( + "setting_name", + ( + "commands:strike:performed-manually-warning-location", + "commands:strike:timeout-duration", + ), + ) + def test_a_value_beginning_with_a_hash_is_kept_as_text(setting_name: str) -> None: + """Test that text that would otherwise be read as a comment is kept.""" + assert parse_setting_value(setting_name, "#staff") == "#staff" + + @staticmethod + @pytest.mark.parametrize( + "setting_name", + ( + "commands:strike:performed-manually-warning-location", + "commands:strike:timeout-duration", + ), + ) + def test_a_value_that_is_not_valid_yaml_is_kept_as_text(setting_name: str) -> None: + """Test that text which happens to be malformed YAML is kept as the text it is.""" + assert parse_setting_value(setting_name, '"unclosed quote') == '"unclosed quote' + + @staticmethod + def test_every_setting_can_be_named() -> None: + """Test that each setting that exists is offered as one that can be changed.""" + SETTINGS_NAMES: Final[Sequence[str]] = config.documented_setting_names() + + assert "commands:ping:easter-egg-probability" in SETTINGS_NAMES + assert list(SETTINGS_NAMES) == sorted(config.get_settings_metadata()) + + @staticmethod + @pytest.mark.parametrize("raw_value", ("1234", '"1234"', "'1234'")) + def test_a_setting_holding_text_keeps_a_value_that_looks_numeric( + raw_value: str, + ) -> None: + """ + Test that a value which looks like a number stays text where text is expected. + + An MSL organisation ID is four or five digits, so somebody setting one will + write it exactly as they see it, without quoting it as YAML would require. + """ + assert parse_setting_value("community-group:msl:organisation-id", raw_value) == "1234" + + @staticmethod + @pytest.mark.parametrize("raw_value", ("null", "NULL", "~", " null ")) + @pytest.mark.parametrize( + "setting_name", + # NOTE: A setting holding text, & one holding anything else, because text is + # otherwise deliberately kept as the text it was typed as. + ("community-group:full-name", "community-group:links:purchase-membership"), + ) + def test_a_setting_written_as_null_is_cleared(setting_name: str, raw_value: str) -> None: + """ + Test that clearing a setting clears it, whatever kind of value it holds. + + A setting declared to hold text would otherwise be set to the word `null` itself, + rather than to nothing at all. + """ + assert parse_setting_value(setting_name, raw_value) is None + + @staticmethod + def test_a_setting_holding_a_sequence_is_not_mistaken_for_text() -> None: + """Test that a list of role names is still read as a list.""" + assert parse_setting_value("commands:stats:displayed-roles", "[Committee]") == [ + "Committee" + ] + + @staticmethod + def test_an_unknown_setting_is_refused() -> None: + """Test that reading a value for a setting that does not exist is refused.""" + with pytest.raises(UnknownSettingError, match="not:a:setting"): + parse_setting_value("not:a:setting", "1") + + +class TestChangingSettings: + """Test case for writing a single setting into the configuration file.""" + + @staticmethod + def test_a_changed_setting_is_applied( + configured: Callable[[str], Path], + ) -> None: + """Test that changing a setting takes effect immediately.""" + configured(COMMENTED_CONFIG) + + RESULT: Final[ConfigReloadResult] = config.set_setting( + "commands:ping:easter-egg-probability", "0.5" + ) + + assert RESULT.changed_settings == {"commands:ping:easter-egg-probability"} + assert ( + config.settings.commands.ping.easter_egg_probability + == CHANGED_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_a_changed_setting_is_written_to_the_file( + configured: Callable[[str], Path], + ) -> None: + """Test that a changed setting survives being loaded again.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + config.set_setting("commands:ping:easter-egg-probability", "0.5") + + assert ( + SettingsDocument.load(CONFIG_FILE_PATH).raw["commands"]["ping"][ + "easter-egg-probability" + ] + == CHANGED_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_changing_a_setting_does_not_write_back_comments( + configured: Callable[[str], Path], + ) -> None: + """Test that rewriting the file leaves out the comments, but keeps every setting.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + config.set_setting("commands:ping:easter-egg-probability", "0.5") + + NEW_FILE_CONTENTS: Final[str] = CONFIG_FILE_PATH.read_text(encoding="utf-8") + + assert "#" not in NEW_FILE_CONTENTS + assert "easter-egg-probability: 0.5" in NEW_FILE_CONTENTS + assert "full-name: Computer Science Society" in NEW_FILE_CONTENTS + + @staticmethod + def test_a_setting_within_an_absent_section_is_created( + configured: Callable[[str], Path], + ) -> None: + """Test that setting a value creates whichever sections are needed to hold it.""" + configured(MINIMAL_CONFIG) + + config.set_setting("reminders:send-get-roles-reminders:interval", "30m") + + assert config.settings.as_flat_file_mapping()[ + "reminders:send-get-roles-reminders:interval" + ] == datetime.timedelta(minutes=30) + + @staticmethod + def test_a_change_needing_a_restart_is_reported( + configured: Callable[[str], Path], + ) -> None: + """Test that changing a setting fixed at start-up says a restart is needed.""" + configured(COMMENTED_CONFIG) + + RESULT: Final[ConfigReloadResult] = config.set_setting( + "reminders:send-get-roles-reminders:interval", "30m" + ) + + assert RESULT.restart_required_settings == { + "reminders:send-get-roles-reminders:interval" + } + + @staticmethod + def test_an_unknown_setting_is_refused(configured: Callable[[str], Path]) -> None: + """Test that changing a setting that does not exist is refused.""" + configured(COMMENTED_CONFIG) + + with pytest.raises(UnknownSettingError): + config.set_setting("not:a:setting", "1") + + +class TestChangingTheFileThatIsRunning: + """Test case for which configuration file a change is made to & read back from.""" + + @staticmethod + def test_a_change_is_read_back_from_the_file_it_was_written_to( + configured: Callable[[str], Path], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """ + Test that a change is applied from the file TeX-Bot is running, not a newer one. + + A change is deliberately written to the file the running configuration was loaded + from. Reading it back out of whichever file would be located now would apply a + configuration that was never the one changed, so the setting just written would + appear not to have been. + """ + RUNNING_CONFIG_FILE_PATH: Final[Path] = configured(MINIMAL_CONFIG) + + OTHER_CONFIG_FILE_PATH: Final[Path] = tmp_path / "somewhere-else.yaml" + OTHER_CONFIG_FILE_PATH.write_text( + f"{MINIMAL_CONFIG}commands:\n ping:\n easter-egg-probability: 0.99\n", + encoding="utf-8", + ) + monkeypatch.setenv( + SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(OTHER_CONFIG_FILE_PATH) + ) + + config.set_setting( + "commands:ping:easter-egg-probability", str(CHANGED_EASTER_EGG_PROBABILITY) + ) + + assert ( + config.settings.commands.ping.easter_egg_probability + == CHANGED_EASTER_EGG_PROBABILITY + ) + assert str(CHANGED_EASTER_EGG_PROBABILITY) in RUNNING_CONFIG_FILE_PATH.read_text( + encoding="utf-8" + ) + assert config.settings.file_path == RUNNING_CONFIG_FILE_PATH + + +class TestRejectedChanges: + """Test case for refusing a change that would produce an invalid configuration.""" + + @staticmethod + def test_an_invalid_value_is_rejected(configured: Callable[[str], Path]) -> None: + """Test that a value outside what a setting allows is refused.""" + configured(COMMENTED_CONFIG) + + with pytest.raises(SettingsValidationError): + config.set_setting("commands:ping:easter-egg-probability", "9.9") + + @staticmethod + def test_a_rejected_change_does_not_touch_the_file( + configured: Callable[[str], Path], + ) -> None: + """ + Test that a refused change leaves the configuration file exactly as it was. + + The change is validated against a copy of the file, so a value that turns out to + be invalid never reaches the file that TeX-Bot would load next. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + with pytest.raises(SettingsValidationError): + config.set_setting("commands:ping:easter-egg-probability", "9.9") + + assert CONFIG_FILE_PATH.read_text(encoding="utf-8") == COMMENTED_CONFIG + + @staticmethod + def test_a_rejected_change_leaves_the_running_configuration_alone( + configured: Callable[[str], Path], + ) -> None: + """Test that a refused change does not disturb the settings already loaded.""" + configured(COMMENTED_CONFIG) + + with pytest.raises(SettingsValidationError): + config.set_setting("commands:ping:easter-egg-probability", "9.9") + + assert ( + config.settings.commands.ping.easter_egg_probability + == DEFAULT_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_a_rejected_new_setting_is_reported_without_a_line_number( + configured: Callable[[str], Path], + ) -> None: + """ + Test that refusing a setting absent from the file is reported, not crashed upon. + + A setting being written for the first time has no line within the file it came + from, so there is no line number to report it against. + """ + configured(MINIMAL_CONFIG) + + with pytest.raises(SettingsValidationError) as validation_error: + config.set_setting("reminders:send-get-roles-reminders:interval", "0s") + + assert "reminders:send-get-roles-reminders:interval" in str(validation_error.value) + + +class TestChangesMadeByHand: + """ + Test case for a change made from within Discord meeting one made by hand. + + A configuration file that has been edited since it was last loaded is refused rather + than merged into, so that a change is only ever made against the configuration that + TeX-Bot is actually running. + """ + + @staticmethod + def _edit_by_hand(config_file_path: Path, original: str, replacement: str) -> None: + """Edit the configuration file directly, as somebody with a text editor would.""" + config_file_path.write_text( + config_file_path.read_text(encoding="utf-8").replace(original, replacement), + encoding="utf-8", + ) + + @staticmethod + @pytest.mark.parametrize( + ("original", "replacement"), + ( + # NOTE: An edit to the setting being changed, to a different setting, one + # adding a setting, & one removing a setting. + ("easter-egg-probability: 0.01", "easter-egg-probability: 0.25"), + ("full-name: Computer Science Society", "full-name: Edited By Hand"), + ("community-group:\n", "auto-add-committee-to-threads: false\ncommunity-group:\n"), + (" full-name: Computer Science Society\n", ""), + ), + ) + def test_a_change_is_refused_while_the_file_has_been_edited( + configured: Callable[[str], Path], original: str, replacement: str + ) -> None: + """Test that any edit made by hand refuses a change made from within Discord.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestChangesMadeByHand._edit_by_hand(CONFIG_FILE_PATH, original, replacement) + CONFIG_FILE_CONTENTS_AFTER_EDIT: Final[str] = CONFIG_FILE_PATH.read_text( + encoding="utf-8" + ) + + with pytest.raises(SettingsFileChangedError): + config.set_setting("commands:ping:easter-egg-probability", "0.5") + + assert CONFIG_FILE_PATH.read_text(encoding="utf-8") == CONFIG_FILE_CONTENTS_AFTER_EDIT + assert ( + config.settings.commands.ping.easter_egg_probability + == DEFAULT_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_a_removal_is_refused_while_the_file_has_been_edited( + configured: Callable[[str], Path], + ) -> None: + """Test that an edit made by hand refuses a removal too, not only a change.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestChangesMadeByHand._edit_by_hand( + CONFIG_FILE_PATH, + "full-name: Computer Science Society", + "full-name: Edited By Hand", + ) + + with pytest.raises(SettingsFileChangedError): + config.unset_setting("commands:ping:easter-egg-probability") + + assert config.settings.community_group.full_name == "Computer Science Society" + + @staticmethod + def test_reloading_first_allows_the_change_to_be_made( + configured: Callable[[str], Path], + ) -> None: + """ + Test that loading the edits made by hand is enough to allow a change again. + + This is what the refusal tells whoever ran the command to do, so it has to be + the case that doing it lets them carry on. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestChangesMadeByHand._edit_by_hand( + CONFIG_FILE_PATH, + "full-name: Computer Science Society", + "full-name: Edited By Hand", + ) + + config.reload_settings() + config.set_setting("commands:ping:easter-egg-probability", "0.5") + + assert config.settings.as_flat_file_mapping()["community-group:full-name"] == ( + "Edited By Hand" + ) + assert ( + config.settings.commands.ping.easter_egg_probability + == CHANGED_EASTER_EGG_PROBABILITY + ) + + @staticmethod + def test_an_edit_to_only_the_comments_does_not_refuse_a_change( + configured: Callable[[str], Path], + ) -> None: + """ + Test that adding a comment by hand does not count as editing the settings. + + Comments are not written back when the file is rewritten, so refusing a change + until such an edit had been reloaded would protect nothing. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestChangesMadeByHand._edit_by_hand( + CONFIG_FILE_PATH, "discord:\n", "# A comment added by hand.\ndiscord:\n" + ) + + config.set_setting("commands:ping:easter-egg-probability", "0.5") + + assert ( + config.settings.commands.ping.easter_egg_probability + == CHANGED_EASTER_EGG_PROBABILITY + ) + assert "# A comment added by hand." not in CONFIG_FILE_PATH.read_text(encoding="utf-8") + + @staticmethod + def test_a_change_made_from_discord_does_not_refuse_the_next_one( + configured: Callable[[str], Path], + ) -> None: + """ + Test that changing a setting does not leave the file looking edited by hand. + + Each change rewrites the file, so the check has to recognise TeX-Bot's own + writing as its own, or no second change could ever be made. + """ + configured(COMMENTED_CONFIG) + + config.set_setting("commands:ping:easter-egg-probability", "0.5") + config.set_setting("community-group:full-name", "CompSoc") + + assert config.settings.as_flat_file_mapping()["community-group:full-name"] == ( + "CompSoc" + ) + + @staticmethod + def test_a_change_is_made_against_the_file_that_was_loaded( + write_config: ConfigWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """ + Test that a change is made to the file the given configuration was loaded from. + + The file TeX-Bot loaded is not necessarily the one that would be located afresh, + so resolving it by location (rather than from the document the change is made + against) would compare against, validate & rewrite an entirely different file. + """ + LOADED_DOCUMENT: Final[SettingsDocument] = SettingsDocument.load( + write_config(COMMENTED_CONFIG) + ) + + OTHER_FILE_PATH: Final[Path] = tmp_path / "elsewhere.yaml" + OTHER_FILE_PATH.write_text(MINIMAL_CONFIG, encoding="utf-8") + monkeypatch.setenv(SETTINGS_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(OTHER_FILE_PATH)) + + UPDATED_DOCUMENT: Final[SettingsDocument] = validated_document_with_setting_set( + "community-group:full-name", "CompSoc", LOADED_DOCUMENT + ) + + assert UPDATED_DOCUMENT.file_path == LOADED_DOCUMENT.file_path + assert OTHER_FILE_PATH.read_text(encoding="utf-8") == MINIMAL_CONFIG + + @staticmethod + def test_an_unedited_file_is_not_reported_as_changed( + configured: Callable[[str], Path], + ) -> None: + """Test that a file nobody has touched is not mistaken for one that was edited.""" + configured(COMMENTED_CONFIG) + + assert not config.settings.file_has_changed() + + @staticmethod + def test_differing_line_endings_are_not_mistaken_for_an_edit( + configured: Callable[[str], Path], + ) -> None: + """ + Test that rewriting the file with other line endings does not count as an edit. + + A configuration file edited upon one operating system & used upon another is + commonplace, & says nothing about whether its settings were changed. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + CONFIG_FILE_PATH.write_bytes( + COMMENTED_CONFIG.replace("\n", "\r\n").encode(encoding="utf-8") + ) + + assert not config.settings.file_has_changed() + + +class TestRemovingSettings: + """Test case for returning a single setting to its default value.""" + + @staticmethod + def test_a_removed_setting_returns_to_its_default( + configured: Callable[[str], Path], + ) -> None: + """Test that removing a setting restores the value it would otherwise have.""" + configured(COMMENTED_CONFIG) + + RESULT: Final[ConfigReloadResult | None] = config.unset_setting( + "community-group:full-name" + ) + + assert RESULT is not None + assert RESULT.changed_settings == {"community-group:full-name"} + assert config.settings.as_flat_file_mapping()["community-group:full-name"] is None + + @staticmethod + def test_removing_a_setting_that_is_not_set_changes_nothing( + configured: Callable[[str], Path], + ) -> None: + """Test that removing a setting absent from the file is reported as such.""" + CONFIG_FILE_PATH: Final[Path] = configured(MINIMAL_CONFIG) + + assert config.unset_setting("community-group:full-name") is None + assert CONFIG_FILE_PATH.read_text(encoding="utf-8") == MINIMAL_CONFIG + + @staticmethod + def test_removing_an_unknown_setting_is_refused( + configured: Callable[[str], Path], + ) -> None: + """Test that removing a setting that does not exist is refused.""" + configured(COMMENTED_CONFIG) + + with pytest.raises(UnknownSettingError): + config.unset_setting("not:a:setting") + + @staticmethod + def test_removing_a_required_setting_is_refused( + configured: Callable[[str], Path], + ) -> None: + """ + Test that a setting TeX-Bot cannot run without is not removed. + + No special knowledge of which settings are required is needed: the configuration + that removing it would produce simply does not validate. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + with pytest.raises(SettingsValidationError): + config.unset_setting("discord:bot-token") + + assert CONFIG_FILE_PATH.read_text(encoding="utf-8") == COMMENTED_CONFIG + assert config.settings.discord.bot_token.get_secret_value() == VALID_BOT_TOKEN + + @staticmethod + def test_a_section_left_empty_is_still_valid( + configured: Callable[[str], Path], + ) -> None: + """ + Test that removing the last setting of a section leaves a usable file. + + A section holding nothing is kept rather than removed, because a section may be + required to be present even when every setting within it is left at its default. + """ + configured(COMMENTED_CONFIG) + + config.unset_setting("commands:ping:easter-egg-probability") + + assert ( + config.settings.commands.ping.easter_egg_probability + == DEFAULT_EASTER_EGG_PROBABILITY + ) + assert config.reload_settings().changed_settings == set() + + @staticmethod + def test_removing_a_setting_an_optional_section_needs_removes_the_section( + configured: Callable[[str], Path], + ) -> None: + """ + Test that the Discord log channel can be turned off by removing its webhook URL. + + The section cannot be used without its webhook URL, so removing only the URL would + leave a configuration that is not valid, & the removal would be refused. + """ + CONFIG_FILE_PATH: Final[Path] = configured( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + f" log-level: ERROR\n" + ) + + RESULT: Final[ConfigReloadResult | None] = config.unset_setting( + "logging:discord-channel:webhook-url" + ) + + assert RESULT is not None + assert config.settings.logging.discord_channel is None + assert "discord-channel" not in CONFIG_FILE_PATH.read_text(encoding="utf-8") + + @staticmethod + def test_removing_an_optional_setting_of_an_optional_section_keeps_the_section( + configured: Callable[[str], Path], + ) -> None: + """Test that only a setting the section needs takes the whole section with it.""" + configured( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + f" log-level: ERROR\n" + ) + + config.unset_setting("logging:discord-channel:log-level") + + assert config.settings.logging.discord_channel is not None + assert str(config.settings.logging.discord_channel.webhook_url) == VALID_WEBHOOK_URL + + @staticmethod + def test_removing_the_only_section_beneath_a_comment_leaves_a_loadable_file( + configured: Callable[[str], Path], + ) -> None: + """ + Test that the Discord log channel can be turned off beneath a comment. + + Writing the comment back would place it at an indentation that is not valid YAML, + leaving a file that TeX-Bot could not start from. + """ + CONFIG_FILE_PATH: Final[Path] = configured( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" # Relay errors to the committee's Discord channel.\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n" + ) + + config.unset_setting("logging:discord-channel:webhook-url") + + assert config.settings.logging.discord_channel is None + assert SettingsDocument.load(CONFIG_FILE_PATH).raw["logging"] == {} + + +class TestLoggingChanges: + """Test case for changing a setting that controls where logs are recorded.""" + + @staticmethod + def test_an_unusable_log_file_changes_nothing( + configured: Callable[[str], Path], tmp_path: Path + ) -> None: + """ + Test that naming a log file within a missing folder leaves everything as it was. + + Applying such a file would fail only after the configuration file had been + rewritten, leaving the change saved but Discord API logs no longer recorded. + """ + ORIGINAL_FILE_CONTENTS: Final[str] = ( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-api:\n" + f" enabled: true\n" + f" file-name: {tmp_path / 'discord.log'}\n" + ) + CONFIG_FILE_PATH: Final[Path] = configured(ORIGINAL_FILE_CONTENTS) + + with pytest.raises(SettingsValidationError, match="does not exist"): + config.set_setting( + "logging:discord-api:file-name", str(tmp_path / "missing" / "discord.log") + ) + + assert CONFIG_FILE_PATH.read_text(encoding="utf-8") == ORIGINAL_FILE_CONTENTS + assert config.settings.logging.discord_api.file_name == str(tmp_path / "discord.log") + + +class TestDescribingAnEditedFile: + """Test case for showing what an edit made by hand would change a setting to.""" + + @staticmethod + def _edit_by_hand(config_file_path: Path, original: str, replacement: str) -> None: + """Edit the configuration file directly, as somebody with a text editor would.""" + config_file_path.write_text( + config_file_path.read_text(encoding="utf-8").replace(original, replacement), + encoding="utf-8", + ) + + @staticmethod + def test_the_value_within_the_file_is_shown_alongside_the_loaded_one( + configured: Callable[[str], Path], + ) -> None: + """Test that an edited setting shows both what was loaded & what the file holds.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, + "easter-egg-probability: 0.01", + "easter-egg-probability: 0.25", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "commands:ping:easter-egg-probability", + config.settings.commands.ping.easter_egg_probability, + secret=False, + ) + + assert "last loaded" in DESCRIPTION + assert "`0.01`" in DESCRIPTION + assert "within the file" in DESCRIPTION + assert "`0.25`" in DESCRIPTION + assert "/config reload" in DESCRIPTION + + @staticmethod + def test_a_duration_within_the_file_is_shown_readably( + configured: Callable[[str], Path], + ) -> None: + """Test that a duration held by the file is shown the way it is written.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, + "commands:\n", + "commands:\n strike:\n timeout-duration: 1h30m\n", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "commands:strike:timeout-duration", + config.settings.commands.strike.timeout_duration, + secret=False, + ) + + assert "`1d`" in DESCRIPTION + assert "`1h30m`" in DESCRIPTION + + @staticmethod + def test_an_edit_elsewhere_says_this_setting_is_unaffected( + configured: Callable[[str], Path], + ) -> None: + """Test that an edit to another setting does not claim this one has changed.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, + "full-name: Computer Science Society", + "full-name: Edited By Hand", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "commands:ping:easter-egg-probability", + config.settings.commands.ping.easter_egg_probability, + secret=False, + ) + + assert "though not this setting" in DESCRIPTION + assert "/config reload" in DESCRIPTION + + @staticmethod + def test_a_secret_within_the_file_is_never_shown( + configured: Callable[[str], Path], + ) -> None: + """Test that comparing a secret does not reveal either value.""" + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + EDITED_TOKEN: Final[str] = f"{VALID_BOT_TOKEN[:-4]}wxyz" + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, VALID_BOT_TOKEN, EDITED_TOKEN + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "discord:bot-token", config.settings.discord.bot_token, secret=True + ) + + assert "different value" in DESCRIPTION + assert EDITED_TOKEN not in DESCRIPTION + assert VALID_BOT_TOKEN not in DESCRIPTION + + @staticmethod + def test_a_file_that_cannot_be_loaded_is_reported( + configured: Callable[[str], Path], + ) -> None: + """ + Test that an edit leaving the file invalid is explained rather than shown. + + There is no value to show from a file that would be refused, so the reason it + would be refused is shown instead, which is what needs fixing before reloading. + """ + CONFIG_FILE_PATH: Final[Path] = configured(COMMENTED_CONFIG) + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, + "easter-egg-probability: 0.01", + "easter-egg-probability: 9.9", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "commands:ping:easter-egg-probability", + config.settings.commands.ping.easter_egg_probability, + secret=False, + ) + + assert "cannot be loaded" in DESCRIPTION + assert "less than or equal to 1" in DESCRIPTION + + @staticmethod + def test_a_setting_added_by_hand_is_shown_against_its_default( + configured: Callable[[str], Path], + ) -> None: + """Test that a setting added by hand is compared against the default in use.""" + CONFIG_FILE_PATH: Final[Path] = configured(MINIMAL_CONFIG) + + TestDescribingAnEditedFile._edit_by_hand( + CONFIG_FILE_PATH, + "discord:\n", + "auto-add-committee-to-threads: false\ndiscord:\n", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "auto-add-committee-to-threads", + config.settings.auto_add_committee_to_threads, + secret=False, + ) + + assert "`true`" in DESCRIPTION + assert "`false`" in DESCRIPTION + + +class TestSettingsWithinAnOmittedSection: + """Test case for a setting whose whole section has been left out of the file.""" + + @staticmethod + def test_its_value_can_be_read_without_being_written( + configured: Callable[[str], Path], + ) -> None: + """ + Test that a setting within an omitted section reads as unset, rather than failing. + + Such a setting has no entry of its own once the settings are flattened, because + the section holding it collapses to a single empty value, yet it is still offered + as a setting that can be viewed. + """ + OMITTED_SETTING_NAME: Final[str] = "logging:discord-channel:webhook-url" + + configured(MINIMAL_CONFIG) + + assert OMITTED_SETTING_NAME in config.documented_setting_names() + assert config.settings.as_flat_mapping().get(OMITTED_SETTING_NAME) is None + + @staticmethod + def test_the_file_holding_it_is_compared_without_failing( + configured: Callable[[str], Path], + ) -> None: + """Test that adding such a section by hand is described rather than crashed upon.""" + CONFIG_FILE_PATH: Final[Path] = configured(MINIMAL_CONFIG) + + CONFIG_FILE_PATH.write_text( + f"{MINIMAL_CONFIG}" + f"logging:\n" + f" discord-channel:\n" + f" webhook-url: {VALID_WEBHOOK_URL}\n", + encoding="utf-8", + ) + + DESCRIPTION: Final[str] = config.format_file_difference( + "logging:discord-channel:log-level", None, secret=False + ) + + assert "`WARNING`" in DESCRIPTION + + +class TestDisplayingValues: + """Test case for rendering a setting's value into something readable.""" + + @staticmethod + @pytest.mark.parametrize( + ("duration", "expected_display"), + ( + (datetime.timedelta(hours=24), "`1d`"), + (datetime.timedelta(minutes=30), "`30m`"), + (datetime.timedelta(hours=1, minutes=30), "`1h30m`"), + (datetime.timedelta(days=1, hours=16), "`1d16h`"), + (datetime.timedelta(seconds=45), "`45s`"), + (datetime.timedelta(0), "`0s`"), + ), + ) + def test_a_duration_is_shown_in_the_format_it_is_written_in( + duration: datetime.timedelta, expected_display: str + ) -> None: + """Test that a length of time is shown the way it would be written in the file.""" + assert format_setting_value(duration, secret=False) == expected_display + + @staticmethod + def test_a_secret_value_is_never_shown() -> None: + """Test that displaying a secret setting does not reveal it.""" + FORMATTED_VALUE: Final[str] = format_setting_value(VALID_BOT_TOKEN, secret=True) + + assert VALID_BOT_TOKEN not in FORMATTED_VALUE + + @staticmethod + def test_an_unset_value_is_shown_as_unset() -> None: + """Test that a setting holding nothing says so, rather than showing nothing.""" + assert "not set" in format_setting_value(None, secret=False) + + @staticmethod + @pytest.mark.parametrize( + ("value", "expected_display"), + ( + (True, "`true`"), + (False, "`false`"), + (("Committee", "Member"), "`Committee`, `Member`"), + (0.01, "`0.01`"), + ), + ) + def test_a_value_is_shown_as_it_is_written(value: object, expected_display: str) -> None: + """Test that each kind of value is shown the way it appears within the file.""" + assert format_setting_value(value, secret=False) == expected_display diff --git a/tests/config/test_logging.py b/tests/config/test_logging.py new file mode 100644 index 000000000..9a05b6828 --- /dev/null +++ b/tests/config/test_logging.py @@ -0,0 +1,391 @@ +"""Test suite for applying the logging configuration.""" + +import logging +from typing import TYPE_CHECKING + +import pytest +from discord_logging.handler import DiscordHandler + +from config._logging import ( + DEFAULT_DISCORD_LOGGING_HANDLER_DISPLAY_NAME, + DISCORD_LOGGER_NAME, + LOGGER_NAME, + apply_logging_settings, + relay_start_up_error_to_discord_log_channel, + set_discord_log_channel_identity, +) +from config._schema import SettingsSchema + +from .conftest import VALID_BOT_TOKEN, VALID_MAIN_GUILD_ID, VALID_WEBHOOK_URL + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, Sequence + from logging import Handler + from pathlib import Path + from typing import Final + + from config._schema import LoggingSettings + +__all__: Sequence[str] = () + + +REQUIRED_SETTINGS: Final[Mapping[str, object]] = { + "discord": {"bot-token": VALID_BOT_TOKEN, "main-guild-id": VALID_MAIN_GUILD_ID} +} + + +def _logging_settings(**logging_overrides: object) -> LoggingSettings: # noqa: CAR150 + """Build the logging section of a validated configuration.""" + return SettingsSchema.model_validate( + {**REQUIRED_SETTINGS, "logging": logging_overrides} + ).logging + + +def _handlers_of_type(logger_name: str, handler_type: type) -> Sequence[Handler]: + """Return every handler of the given type attached to the named logger.""" + return tuple( + handler + for handler in logging.getLogger(logger_name).handlers + if isinstance(handler, handler_type) + ) + + +class TestConsoleLogging: + """Test case for logging to the console output stream.""" + + @staticmethod + def test_console_log_level_is_applied() -> None: + """Test that the configured log level is set upon the logger.""" + apply_logging_settings(_logging_settings(console={"log-level": "WARNING"})) + + assert logging.getLogger(LOGGER_NAME).level == logging.WARNING + + @staticmethod + def test_console_log_level_is_applied_to_the_console_handler() -> None: + """Test that the console only emits logs meeting its own configured level.""" + apply_logging_settings(_logging_settings(console={"log-level": "WARNING"})) + + assert _handlers_of_type(LOGGER_NAME, logging.StreamHandler)[0].level == ( + logging.WARNING + ) + + @staticmethod + def test_a_console_handler_is_attached() -> None: + """Test that logs are emitted to the console output stream.""" + apply_logging_settings(_logging_settings()) + + assert len(_handlers_of_type(LOGGER_NAME, logging.StreamHandler)) == 1 + + @staticmethod + def test_console_logs_are_not_passed_to_the_root_logger() -> None: + """ + Test that TeX-Bot's own logs stop at its own logger. + + Propagating them would emit each record a second time through whichever handler + the root logger happens to hold. + """ + apply_logging_settings(_logging_settings()) + + assert logging.getLogger(LOGGER_NAME).propagate is False + + @staticmethod + def test_applying_settings_repeatedly_does_not_accumulate_handlers() -> None: + """ + Test that applying the logging configuration many times attaches one handler. + + Handlers are replaced rather than added to, because an accumulated handler + would cause every log record to be emitted more than once. + """ + for log_level in ("DEBUG", "INFO", "WARNING", "ERROR"): + apply_logging_settings(_logging_settings(console={"log-level": log_level})) + + assert len(_handlers_of_type(LOGGER_NAME, logging.StreamHandler)) == 1 + + @staticmethod + def test_a_file_handler_is_not_removed_alongside_the_console_handler( + tmp_path: Path, + ) -> None: + """ + Test that replacing the console handler leaves any file handler in place. + + `FileHandler` subclasses `StreamHandler`, so removing every stream handler in + order to replace the console one would otherwise also remove a file handler that + a different logging destination is responsible for. + """ + file_handler: Handler = logging.FileHandler( + filename=tmp_path / "tex-bot.log", encoding="utf-8", mode="a" + ) + logging.getLogger(LOGGER_NAME).addHandler(file_handler) + + try: + apply_logging_settings(_logging_settings(console={"log-level": "INFO"})) + + assert file_handler in logging.getLogger(LOGGER_NAME).handlers + finally: + file_handler.close() + + +class TestDiscordChannelLogging: + """Test case for relaying error logs to a Discord log channel.""" + + @staticmethod + def test_no_handler_is_attached_when_the_section_is_omitted() -> None: + """Test that omitting the Discord log-channel section attaches no handler.""" + apply_logging_settings(_logging_settings()) + + assert not _handlers_of_type(LOGGER_NAME, DiscordHandler) + + @staticmethod + def test_a_handler_is_attached_when_a_webhook_is_configured() -> None: + """Test that configuring a webhook URL relays logs to that Discord channel.""" + apply_logging_settings( + _logging_settings( + **{"discord-channel": {"webhook-url": VALID_WEBHOOK_URL, "log-level": "ERROR"}} + ) + ) + + DISCORD_HANDLERS: Final[Sequence[Handler]] = _handlers_of_type( + LOGGER_NAME, DiscordHandler + ) + + assert len(DISCORD_HANDLERS) == 1 + assert DISCORD_HANDLERS[0].level == logging.ERROR + + @staticmethod + def test_a_level_below_the_console_level_still_reaches_the_log_channel() -> None: + """ + Test that the log channel receives logs which the console does not emit. + + TeX-Bot's logger drops a record before any handler sees it, so the logger must + let through every record that the Discord log channel's own level accepts, + even when the console is set to a higher level. + """ + apply_logging_settings( + _logging_settings( + console={"log-level": "ERROR"}, + **{"discord-channel": {"webhook-url": VALID_WEBHOOK_URL, "log-level": "INFO"}}, + ) + ) + + assert logging.getLogger(LOGGER_NAME).isEnabledFor(logging.INFO) + assert _handlers_of_type(LOGGER_NAME, logging.StreamHandler)[0].level == ( + logging.ERROR + ) + + @staticmethod + def test_removing_the_webhook_detaches_the_handler() -> None: + """Test that removing the Discord log-channel section stops relaying logs.""" + apply_logging_settings( + _logging_settings(**{"discord-channel": {"webhook-url": VALID_WEBHOOK_URL}}) + ) + assert _handlers_of_type(LOGGER_NAME, DiscordHandler) + + apply_logging_settings(_logging_settings()) + + assert not _handlers_of_type(LOGGER_NAME, DiscordHandler) + + +@pytest.fixture() +def _placeholder_identity() -> Iterator[None]: + """Begin from the placeholder name & avatar, restoring them after the test.""" + set_discord_log_channel_identity(DEFAULT_DISCORD_LOGGING_HANDLER_DISPLAY_NAME, None) + + yield + + set_discord_log_channel_identity(DEFAULT_DISCORD_LOGGING_HANDLER_DISPLAY_NAME, None) + + +def _discord_log_channel_handler() -> DiscordHandler: + """Return the single handler relaying logs into the Discord log channel.""" + DISCORD_HANDLERS: Final[Sequence[Handler]] = _handlers_of_type(LOGGER_NAME, DiscordHandler) + + assert len(DISCORD_HANDLERS) == 1 + assert isinstance(DISCORD_HANDLERS[0], DiscordHandler) + + return DISCORD_HANDLERS[0] + + +@pytest.mark.usefixtures("_placeholder_identity") +class TestDiscordChannelIdentity: + """Test case for the name & avatar that logs are relayed under.""" + + @staticmethod + def test_the_handler_already_relaying_logs_is_given_the_identity() -> None: + """Test that logging in to Discord renames the handler already in use.""" + apply_logging_settings( + _logging_settings(**{"discord-channel": {"webhook-url": VALID_WEBHOOK_URL}}) + ) + + set_discord_log_channel_identity("CSS Bot", "https://cdn.discordapp.com/a.png") + + assert _discord_log_channel_handler().service_name == "CSS Bot" + assert _discord_log_channel_handler().avatar_url == ( + "https://cdn.discordapp.com/a.png" + ) + + @staticmethod + def test_the_identity_is_kept_by_a_later_reload() -> None: + """ + Test that the handler created afresh by a reload keeps TeX-Bot's own name. + + Each reload replaces the handler, & TeX-Bot only logs in to Discord once. + """ + set_discord_log_channel_identity("CSS Bot", None) + + apply_logging_settings( + _logging_settings(**{"discord-channel": {"webhook-url": VALID_WEBHOOK_URL}}) + ) + + assert _discord_log_channel_handler().service_name == "CSS Bot" + + +@pytest.fixture() +def relayed_messages(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Return a record of every message relayed to a Discord webhook.""" + messages: list[str] = [] + + def _emit(_handler: DiscordHandler, record: logging.LogRecord) -> None: + messages.append(record.getMessage()) + + monkeypatch.setattr(DiscordHandler, "emit", _emit) + + return messages + + +def test_a_start_up_error_is_relayed_to_the_given_webhook( + relayed_messages: list[str], +) -> None: + """Test that an error stopping TeX-Bot from starting up is sent to the channel.""" + relay_start_up_error_to_discord_log_channel( + ValueError("A setting is 100% wrong"), VALID_WEBHOOK_URL + ) + + assert relayed_messages == ["A setting is 100% wrong"] + + +class TestDiscordAPILogging: + """Test case for recording the logs emitted by the Discord API wrapper.""" + + @staticmethod + def test_no_handler_is_attached_when_disabled() -> None: + """Test that Discord API logs are not recorded unless they are enabled.""" + apply_logging_settings(_logging_settings(**{"discord-api": {"enabled": False}})) + + assert not _handlers_of_type(DISCORD_LOGGER_NAME, logging.FileHandler) + + @staticmethod + def test_a_file_handler_is_attached_when_enabled(tmp_path: Path) -> None: + """Test that enabling Discord API logging writes them to the configured file.""" + LOG_FILE_PATH: Final[Path] = tmp_path / "discord.log" + + apply_logging_settings( + _logging_settings( + **{ + "discord-api": { + "enabled": True, + "log-level": "DEBUG", + "file-name": str(LOG_FILE_PATH), + } + } + ) + ) + + FILE_HANDLERS: Final[Sequence[Handler]] = _handlers_of_type( + DISCORD_LOGGER_NAME, logging.FileHandler + ) + + assert len(FILE_HANDLERS) == 1 + assert logging.getLogger(DISCORD_LOGGER_NAME).level == logging.DEBUG + + @staticmethod + def test_discord_api_logs_are_captured_only_while_they_are_recorded( + tmp_path: Path, + ) -> None: + """ + Test that Discord API logs are released back once they stop being recorded. + + While they are being recorded they are held at their own logger, so that they do + not also appear amongst TeX-Bot's own console output. + """ + apply_logging_settings( + _logging_settings( + **{ + "discord-api": { + "enabled": True, + "file-name": str(tmp_path / "discord.log"), + } + } + ) + ) + assert logging.getLogger(DISCORD_LOGGER_NAME).propagate is False + + apply_logging_settings(_logging_settings(**{"discord-api": {"enabled": False}})) + + assert logging.getLogger(DISCORD_LOGGER_NAME).propagate is True + + @staticmethod + def test_the_log_file_is_released_when_recording_stops(tmp_path: Path) -> None: + """ + Test that the Discord API log file is closed once it stops being written to. + + Leaving the handler's file open would hold a lock upon it for as long as TeX-Bot + continued to run, so each reload would strand another one. + """ + LOG_FILE_PATH: Final[Path] = tmp_path / "discord.log" + + apply_logging_settings( + _logging_settings( + **{"discord-api": {"enabled": True, "file-name": str(LOG_FILE_PATH)}} + ) + ) + apply_logging_settings(_logging_settings(**{"discord-api": {"enabled": False}})) + + LOG_FILE_PATH.unlink() + + assert not LOG_FILE_PATH.exists() + + @staticmethod + def test_disabling_afterwards_detaches_the_handler(tmp_path: Path) -> None: + """Test that disabling Discord API logging stops recording it.""" + apply_logging_settings( + _logging_settings( + **{ + "discord-api": { + "enabled": True, + "file-name": str(tmp_path / "discord.log"), + } + } + ) + ) + assert _handlers_of_type(DISCORD_LOGGER_NAME, logging.FileHandler) + + apply_logging_settings(_logging_settings(**{"discord-api": {"enabled": False}})) + + assert not _handlers_of_type(DISCORD_LOGGER_NAME, logging.FileHandler) + + @staticmethod + def test_disabling_afterwards_restores_the_original_log_level(tmp_path: Path) -> None: + """ + Test that disabling Discord API logging leaves no configured level behind. + + Disabling these logs also passes them back to the root logger. A level left over + from when they were enabled would send every record meeting it there rather than + discarding it, so turning the logs off would make them noisier, not quieter. + """ + apply_logging_settings( + _logging_settings( + **{ + "discord-api": { + "enabled": True, + "log-level": "DEBUG", + "file-name": str(tmp_path / "discord.log"), + } + } + ) + ) + assert logging.getLogger(DISCORD_LOGGER_NAME).level == logging.DEBUG + + apply_logging_settings(_logging_settings(**{"discord-api": {"enabled": False}})) + + assert logging.getLogger(DISCORD_LOGGER_NAME).level == logging.NOTSET + assert logging.getLogger(DISCORD_LOGGER_NAME).propagate diff --git a/tests/config/test_messages.py b/tests/config/test_messages.py new file mode 100644 index 000000000..484d72389 --- /dev/null +++ b/tests/config/test_messages.py @@ -0,0 +1,230 @@ +"""Test suite for loading the response messages TeX-Bot sends into Discord.""" + +import json +from typing import TYPE_CHECKING + +import pytest + +from config._messages import ( + MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, + MessagesAccessor, +) +from exceptions import ( + ImproperlyConfiguredError, + MessagesJSONFileMissingKeyError, + MessagesJSONFileValueError, +) + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping, Sequence + from pathlib import Path + from typing import Final + + type MessagesWriter = "Callable[[object], Path]" + +__all__: Sequence[str] = () + + +VALID_MESSAGES: Final[Mapping[str, object]] = { + "welcome_messages": ["Welcome!", "Hello there!"], + "roles_messages": ["Get your roles here."], +} + + +@pytest.fixture() +def write_messages(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> MessagesWriter: + """Return a callable writing the given messages & pointing TeX-Bot at them.""" + + def _write_messages(raw_messages: object) -> Path: + messages_file_path: Path = tmp_path / "messages.json" + messages_file_path.write_text( + raw_messages if isinstance(raw_messages, str) else json.dumps(raw_messages), + encoding="utf-8", + ) + monkeypatch.setenv( + MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(messages_file_path) + ) + return messages_file_path + + return _write_messages + + +class TestLoading: + """Test case for reading the messages file.""" + + @staticmethod + def test_valid_messages_are_loaded(write_messages: MessagesWriter) -> None: + """Test that both sets of messages are read from a valid file.""" + write_messages(VALID_MESSAGES) + messages: MessagesAccessor = MessagesAccessor() + + messages.reload() + + assert messages.is_loaded + assert messages.welcome_messages == frozenset({"Welcome!", "Hello there!"}) + assert messages.roles_messages == frozenset({"Get your roles here."}) + + @staticmethod + def test_accessing_messages_before_loading_is_refused() -> None: + """Test that reading messages before any are loaded is refused.""" + messages: MessagesAccessor = MessagesAccessor() + + assert not messages.is_loaded + + with pytest.raises(RuntimeError, match="before they have been loaded"): + _ = messages.welcome_messages + + @staticmethod + def test_a_missing_file_is_reported( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Test that naming a messages file that does not exist is reported clearly.""" + monkeypatch.setenv( + MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(tmp_path / "absent.json") + ) + + with pytest.raises(ImproperlyConfiguredError, match="must be a path"): + MessagesAccessor().reload() + + @staticmethod + def test_malformed_json_is_reported(write_messages: MessagesWriter) -> None: + """Test that a file that is not valid JSON is reported clearly.""" + write_messages("{not valid json") + + with pytest.raises(ImproperlyConfiguredError, match="decoded"): + MessagesAccessor().reload() + + @staticmethod + def test_a_file_that_is_not_utf_8_is_reported(write_messages: MessagesWriter) -> None: + """ + Test that a file saved in a different text encoding is reported clearly. + + A file saved as Latin-1 holding an accented character cannot be read as UTF-8, + & would otherwise fail with an error that no caller expects. + """ + write_messages(VALID_MESSAGES).write_bytes( + json.dumps( + {"welcome_messages": ["Bienvenue à la société"], "roles_messages": ["Rôles"]}, + ensure_ascii=False, + ).encode("latin-1") + ) + + with pytest.raises(ImproperlyConfiguredError, match="must be saved as UTF-8"): + MessagesAccessor().reload() + + @staticmethod + @pytest.mark.parametrize("raw_messages", (["a", "list"], "a string", 42)) + def test_json_that_is_not_an_object_is_reported( + write_messages: MessagesWriter, raw_messages: object + ) -> None: + """Test that a messages file not holding an object of message sets is rejected.""" + write_messages(raw_messages) + + with pytest.raises(ImproperlyConfiguredError, match="decoded"): + MessagesAccessor().reload() + + +class TestMessageSetValidation: + """Test case for the structure each set of messages must have.""" + + @staticmethod + @pytest.mark.parametrize("missing_key", ("welcome_messages", "roles_messages")) + def test_a_missing_message_set_is_reported( + write_messages: MessagesWriter, missing_key: str + ) -> None: + """Test that omitting either set of messages is reported clearly.""" + write_messages( + {key: value for key, value in VALID_MESSAGES.items() if key != missing_key} + ) + + with pytest.raises(MessagesJSONFileMissingKeyError): + MessagesAccessor().reload() + + @staticmethod + @pytest.mark.parametrize("invalid_value", ([], None, 42, {})) + def test_an_empty_or_non_iterable_message_set_is_reported( + write_messages: MessagesWriter, invalid_value: object + ) -> None: + """Test that a set of messages that holds no messages is rejected.""" + write_messages({**VALID_MESSAGES, "welcome_messages": invalid_value}) + + with pytest.raises(MessagesJSONFileValueError): + MessagesAccessor().reload() + + @staticmethod + def test_a_string_is_not_accepted_as_a_set_of_messages( + write_messages: MessagesWriter, + ) -> None: + """ + Test that a single string is not treated as a set of messages. + + A string is iterable, so without an explicit check it would be accepted and + silently split into one message per character. + """ + write_messages({**VALID_MESSAGES, "welcome_messages": "Welcome!"}) + + with pytest.raises(MessagesJSONFileValueError): + MessagesAccessor().reload() + + @staticmethod + def test_an_object_is_not_accepted_as_a_set_of_messages( + write_messages: MessagesWriter, + ) -> None: + """ + Test that a JSON object is not treated as a set of messages. + + An object is iterable too, so without an explicit check it would be accepted and + silently reduced to its own keys, discarding every message it holds. + """ + write_messages({**VALID_MESSAGES, "welcome_messages": {"Welcome!": "Hello there!"}}) + + with pytest.raises(MessagesJSONFileValueError): + MessagesAccessor().reload() + + @staticmethod + def test_messages_that_are_not_strings_are_read_as_text( + write_messages: MessagesWriter, + ) -> None: + """Test that a message written as a number is read as the text of that number.""" + write_messages({**VALID_MESSAGES, "roles_messages": [42, "Get your roles here."]}) + messages: MessagesAccessor = MessagesAccessor() + + messages.reload() + + assert messages.roles_messages == frozenset({"42", "Get your roles here."}) + + +class TestFailedReloads: + """Test case for what happens when messages cannot be reloaded.""" + + @staticmethod + def test_a_failed_reload_leaves_previously_loaded_messages_intact( + write_messages: MessagesWriter, + ) -> None: + """ + Test that failing to reload does not discard the messages already loaded. + + Both sets are read before either is stored, so a file that is only partly + valid cannot leave one set updated and the other stale. + """ + write_messages(VALID_MESSAGES) + messages: MessagesAccessor = MessagesAccessor() + messages.reload() + + write_messages({"welcome_messages": ["Still valid."]}) + + with pytest.raises(MessagesJSONFileMissingKeyError): + messages.reload() + + assert messages.welcome_messages == frozenset({"Welcome!", "Hello there!"}) + assert messages.roles_messages == frozenset({"Get your roles here."}) + + +def test_messages_are_deduplicated(write_messages: MessagesWriter) -> None: + """Test that a message repeated within the file is only held once.""" + write_messages({**VALID_MESSAGES, "roles_messages": ["Same", "Same", "Different"]}) + messages: MessagesAccessor = MessagesAccessor() + + messages.reload() + + assert messages.roles_messages == frozenset({"Same", "Different"}) diff --git a/tests/config/test_reload.py b/tests/config/test_reload.py new file mode 100644 index 000000000..2b047d6a6 --- /dev/null +++ b/tests/config/test_reload.py @@ -0,0 +1,395 @@ +"""Test suite for reloading configuration through the config package's public surface.""" + +import logging +from typing import TYPE_CHECKING + +import pytest +from discord_logging.handler import DiscordHandler + +import config +from config import SettingsValidationError +from config._accessor import SettingsAccessor +from config._messages import MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME +from exceptions import ImproperlyConfiguredError + +from .conftest import MINIMAL_CONFIG, VALID_BOT_TOKEN, VALID_WEBHOOK_URL + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from pathlib import Path + from typing import Final + + from config import ConfigReloadResult + + type ConfigWriter = "Callable[[str], Path]" + +__all__: Sequence[str] = () + + +CONFIG_WITH_TASK_SETTINGS: Final[str] = f"""\ +discord: + bot-token: {VALID_BOT_TOKEN} + main-guild-id: 1234567890123456789 +community-group: + links: {{}} + msl: {{}} +logging: + console: + log-level: INFO +reminders: + send-get-roles-reminders: + enabled: true + interval: 6h + delay: 1d16h +""" + + +@pytest.fixture(autouse=True) +def _unloaded_settings(monkeypatch: pytest.MonkeyPatch) -> None: + """ + Replace the shared settings accessor with one holding no configuration. + + The accessor is a module-level singleton, so without this each test would begin + holding whatever the previous test had loaded, and would report changes relative + to it. Reloading is defined in terms of what changed, so that would make the + results depend upon the order the tests happened to run in. + """ + monkeypatch.setattr(config, "settings", SettingsAccessor()) + + +@pytest.fixture() +def configured( + write_config: ConfigWriter, monkeypatch: pytest.MonkeyPatch +) -> Callable[[str], ConfigReloadResult]: + """ + Return a callable writing the given configuration & reloading it. + + Reloading through the package's public surface reads whichever file the + `TEX_BOT_CONFIG_PATH` environment variable names, so it is pointed at a temporary + file for the duration of each test. + """ + + def _configure(raw_yaml: str) -> ConfigReloadResult: + monkeypatch.setenv("TEX_BOT_CONFIG_PATH", str(write_config(raw_yaml))) + return config.reload_settings() + + return _configure + + +class TestReloadResult: + """Test case for what a reload reports back to its caller.""" + + @staticmethod + def test_reloading_an_unchanged_configuration_reports_nothing( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that reloading without editing the file reports no changes.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + assert configured(CONFIG_WITH_TASK_SETTINGS).changed_settings == set() + + @staticmethod + def test_a_changed_setting_is_reported( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that editing one setting reports exactly that setting.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + RESULT: Final[ConfigReloadResult] = configured( + CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", "log-level: DEBUG") + ) + + assert RESULT.changed_settings == {"logging:console:log-level"} + + @staticmethod + def test_an_invalid_configuration_is_rejected( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that a configuration failing validation is refused.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + with pytest.raises(SettingsValidationError): + configured( + CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", "log-level: NONSENSE") + ) + + @staticmethod + def test_an_invalid_configuration_leaves_the_previous_one_running( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that a rejected reload does not disturb the running configuration.""" + configured(CONFIG_WITH_TASK_SETTINGS) + PREVIOUS_LOG_LEVEL: Final[object] = config.settings.logging.console.log_level + + with pytest.raises(SettingsValidationError): + configured( + CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", "log-level: NONSENSE") + ) + + assert config.settings.logging.console.log_level == PREVIOUS_LOG_LEVEL + + +class TestSettingsHeldUntilRestart: + """Test case for keeping each setting that requires a restart at its start-up value.""" + + @staticmethod + def test_a_setting_requiring_a_restart_keeps_its_start_up_value( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """ + Test that reloading does not apply a setting that requires a restart. + + Parts of TeX-Bot read such a setting again upon every use, so applying a new + value would leave TeX-Bot running partly with the old value & partly the new one. + """ + configured(CONFIG_WITH_TASK_SETTINGS) + + configured( + CONFIG_WITH_TASK_SETTINGS.replace( + "main-guild-id: 1234567890123456789", "main-guild-id: 9876543210987654321" + ) + ) + + assert config.settings.discord.main_guild_id == 1234567890123456789 + assert config.settings.values_awaiting_restart == { + "discord:main-guild-id": 9876543210987654321 + } + + @staticmethod + def test_a_live_setting_changed_alongside_one_requiring_a_restart_is_applied( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that holding back one setting does not hold back the rest of a reload.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + configured( + CONFIG_WITH_TASK_SETTINGS.replace( + "main-guild-id: 1234567890123456789", "main-guild-id: 9876543210987654321" + ).replace("log-level: INFO", "log-level: DEBUG") + ) + + assert config.settings.logging.console.log_level == "DEBUG" + assert config.settings.discord.main_guild_id == 1234567890123456789 + + @staticmethod + def test_changing_a_setting_back_to_its_start_up_value_needs_no_restart( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that undoing a change awaiting a restart leaves nothing awaiting one.""" + configured(CONFIG_WITH_TASK_SETTINGS) + configured( + CONFIG_WITH_TASK_SETTINGS.replace( + "main-guild-id: 1234567890123456789", "main-guild-id: 9876543210987654321" + ) + ) + + RESULT: Final[ConfigReloadResult] = configured(CONFIG_WITH_TASK_SETTINGS) + + assert RESULT.changed_settings == {"discord:main-guild-id"} + assert RESULT.restart_required_settings == set() + assert config.settings.values_awaiting_restart == {} + + +class TestRestartRequiredClassification: + """Test case for identifying which changes cannot take effect until a restart.""" + + @staticmethod + def test_a_live_setting_is_not_reported_as_needing_a_restart( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that a setting read at the point of use needs no restart.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + RESULT: Final[ConfigReloadResult] = configured( + CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", "log-level: DEBUG") + ) + + assert RESULT.restart_required_settings == set() + + @staticmethod + @pytest.mark.parametrize( + ("original", "replacement", "expected_setting"), + ( + ( + "main-guild-id: 1234567890123456789", + "main-guild-id: 9876543210987654321", + "discord:main-guild-id", + ), + ( + "interval: 6h", + "interval: 30m", + "reminders:send-get-roles-reminders:interval", + ), + ( + "enabled: true", + "enabled: false", + "reminders:send-get-roles-reminders:enabled", + ), + ), + ) + def test_a_setting_fixed_at_start_up_is_reported_as_needing_a_restart( + configured: Callable[[str], ConfigReloadResult], + original: str, + replacement: str, + expected_setting: str, + ) -> None: + """Test that a setting which cannot be applied while running is flagged.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + RESULT: Final[ConfigReloadResult] = configured( + CONFIG_WITH_TASK_SETTINGS.replace(original, replacement) + ) + + assert RESULT.restart_required_settings == {expected_setting} + + @staticmethod + def test_a_reminder_delay_does_not_require_a_restart( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """ + Test that changing how long to wait before a reminder needs no restart. + + Unlike the interval of the task that sends them, a delay is read from the + settings accessor at the moment it is used. + """ + configured(CONFIG_WITH_TASK_SETTINGS) + + RESULT: Final[ConfigReloadResult] = configured( + CONFIG_WITH_TASK_SETTINGS.replace("delay: 1d16h", "delay: 2d") + ) + + assert RESULT.changed_settings == {"reminders:send-get-roles-reminders:delay"} + assert RESULT.restart_required_settings == set() + + @staticmethod + def test_settings_needing_a_restart_are_a_subset_of_those_that_changed( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that nothing is reported as needing a restart unless it actually changed.""" + RESULT: Final[ConfigReloadResult] = configured(CONFIG_WITH_TASK_SETTINGS) + + assert RESULT.restart_required_settings <= RESULT.changed_settings + + +class TestLoggingApplication: + """Test case for applying logging settings as part of a reload.""" + + @staticmethod + def test_changing_the_console_log_level_takes_effect( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """Test that a new console log level is applied to the logger immediately.""" + configured(CONFIG_WITH_TASK_SETTINGS) + + configured(CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", "log-level: DEBUG")) + + assert logging.getLogger("TeX-Bot").level == logging.DEBUG + + @staticmethod + def test_reloading_repeatedly_does_not_accumulate_handlers( + configured: Callable[[str], ConfigReloadResult], + ) -> None: + """ + Test that reloading many times does not add a logging handler each time. + + Accumulating handlers would cause every log record to be emitted repeatedly. + """ + configured(CONFIG_WITH_TASK_SETTINGS) + HANDLER_COUNT_AFTER_FIRST_LOAD: Final[int] = len(logging.getLogger("TeX-Bot").handlers) + + for log_level in ("DEBUG", "WARNING", "ERROR", "INFO"): + configured( + CONFIG_WITH_TASK_SETTINGS.replace("log-level: INFO", f"log-level: {log_level}") + ) + + assert len(logging.getLogger("TeX-Bot").handlers) == HANDLER_COUNT_AFTER_FIRST_LOAD + + +def test_minimal_configuration_reloads( + configured: Callable[[str], ConfigReloadResult], +) -> None: + """Test that a configuration holding only the required settings can be reloaded.""" + assert configured(MINIMAL_CONFIG).changed_settings + + +CONFIG_WITH_LOG_CHANNEL: Final[str] = ( + f"{MINIMAL_CONFIG}logging:\n discord-channel:\n webhook-url: {VALID_WEBHOOK_URL}\n" +) + +INVALID_SETTING: Final[str] = "commands:\n ping:\n easter-egg-probability: 9.9\n" + + +@pytest.fixture() +def relayed_messages(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Return a record of every message relayed to a Discord webhook.""" + messages: list[str] = [] + + def _emit(_handler: DiscordHandler, record: logging.LogRecord) -> None: + messages.append(record.getMessage()) + + monkeypatch.setattr(DiscordHandler, "emit", _emit) + + return messages + + +class TestStartUpErrors: + """Test case for reporting a configuration that stops TeX-Bot from starting up.""" + + @staticmethod + def test_an_invalid_configuration_is_sent_to_the_log_channel( + write_config: ConfigWriter, + monkeypatch: pytest.MonkeyPatch, + relayed_messages: list[str], + ) -> None: + """ + Test that the error is sent to the webhook written within the invalid file. + + Logging cannot be set up from a configuration that is not valid, so the webhook + is read from the file directly, as long as it is valid on its own. + """ + monkeypatch.setenv( + "TEX_BOT_CONFIG_PATH", + str(write_config(f"{CONFIG_WITH_LOG_CHANNEL}{INVALID_SETTING}")), + ) + + with pytest.raises(SettingsValidationError): + config.run_setup() + + assert len(relayed_messages) == 1 + assert "easter-egg-probability" in relayed_messages[0] + + @staticmethod + def test_nothing_is_sent_without_a_valid_webhook( + write_config: ConfigWriter, + monkeypatch: pytest.MonkeyPatch, + relayed_messages: list[str], + ) -> None: + """Test that an invalid configuration naming no usable webhook is only raised.""" + monkeypatch.setenv( + "TEX_BOT_CONFIG_PATH", str(write_config(f"{MINIMAL_CONFIG}{INVALID_SETTING}")) + ) + + with pytest.raises(SettingsValidationError): + config.run_setup() + + assert not relayed_messages + + @staticmethod + def test_an_invalid_messages_file_is_sent_to_the_log_channel( + write_config: ConfigWriter, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + relayed_messages: list[str], + ) -> None: + """Test that a messages file stopping TeX-Bot from starting up is reported too.""" + MESSAGES_FILE_PATH: Final[Path] = tmp_path / "messages.json" + MESSAGES_FILE_PATH.write_text("{not valid json", encoding="utf-8") + monkeypatch.setenv( + MESSAGES_FILE_PATH_ENVIRONMENT_VARIABLE_NAME, str(MESSAGES_FILE_PATH) + ) + monkeypatch.setenv("TEX_BOT_CONFIG_PATH", str(write_config(CONFIG_WITH_LOG_CHANNEL))) + + with pytest.raises(ImproperlyConfiguredError): + config.run_setup() + + assert any("decoded" in relayed_message for relayed_message in relayed_messages) diff --git a/tests/config/test_schema.py b/tests/config/test_schema.py new file mode 100644 index 000000000..3123d8f90 --- /dev/null +++ b/tests/config/test_schema.py @@ -0,0 +1,884 @@ +"""Test suite for the settings schema.""" + +import datetime +from typing import TYPE_CHECKING + +import pytest +from pydantic import ValidationError +from ruamel.yaml import YAML + +from config import get_settings_metadata +from config._schema import LogLevel, SettingsSchema + +from .conftest import ( + DEFAULT_EASTER_EGG_PROBABILITY, + MINIMAL_CONFIG, + VALID_BOT_TOKEN, + VALID_MAIN_GUILD_ID, + VALID_WEBHOOK_URL, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from pathlib import Path + from typing import Final + + from config import ConfigSettingMetadata + +__all__: Sequence[str] = () + + +REQUIRED_SETTINGS: Final[Mapping[str, object]] = { + "discord": {"bot-token": VALID_BOT_TOKEN, "main-guild-id": VALID_MAIN_GUILD_ID} +} + + +def _config(**overrides: object) -> Mapping[str, object]: # noqa: CAR150 + """Build a valid raw configuration, with the given top-level sections replaced.""" + return {**REQUIRED_SETTINGS, **overrides} + + +class TestRequiredSettings: + """Test case for which settings a configuration must provide.""" + + @staticmethod + def test_minimal_configuration_is_valid() -> None: + """Test that a configuration holding only the required settings validates.""" + settings: SettingsSchema = SettingsSchema.model_validate(_config()) + + assert settings.discord.main_guild_id == VALID_MAIN_GUILD_ID + + @staticmethod + @pytest.mark.parametrize("missing_section", ("discord",)) + def test_missing_required_section_is_rejected(missing_section: str) -> None: + """Test that omitting a required section is rejected.""" + raw_settings: dict[str, object] = dict(REQUIRED_SETTINGS) + del raw_settings[missing_section] + + with pytest.raises(ValidationError, match="Field required"): + SettingsSchema.model_validate(raw_settings) + + @staticmethod + def test_unknown_setting_is_rejected() -> None: + """Test that a setting the schema does not declare is rejected.""" + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + SettingsSchema.model_validate(_config(**{"not-a-real-setting": True})) + + @staticmethod + def test_setting_written_with_underscores_is_rejected() -> None: + """ + Test that a setting written with underscores, rather than hyphens, is rejected. + + Every "/config" command finds a setting by its hyphenated name, so a setting + written with underscores could be loaded, but never viewed or changed from Discord. + """ + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + SettingsSchema.model_validate( + _config(commands={"ping": {"easter_egg_probability": 0.5}}) + ) + + @staticmethod + def test_every_optional_section_may_be_omitted() -> None: + """Test that omitting every optional section still produces usable defaults.""" + settings: SettingsSchema = SettingsSchema.model_validate(_config()) + + assert settings.logging.console.log_level == LogLevel.INFO + assert settings.commands.ping.easter_egg_probability == DEFAULT_EASTER_EGG_PROBABILITY + assert settings.reminders.send_get_roles_reminders.enabled is True + assert settings.auto_add_committee_to_threads is True + assert settings.community_group.links.purchase_membership is None + assert settings.community_group.msl.organisation_id is None + + @staticmethod + def test_discord_log_channel_section_is_optional() -> None: + """ + Test that the Discord log-channel section may be omitted from within `logging`. + + This section holds a required webhook URL, so it must be possible to configure + other logging destinations without providing one. + """ + settings: SettingsSchema = SettingsSchema.model_validate( + _config(logging={"console": {"log-level": "DEBUG"}}) + ) + + assert settings.logging.discord_channel is None + assert settings.logging.console.log_level == LogLevel.DEBUG + + @staticmethod + def test_discord_log_channel_requires_a_webhook_url() -> None: + """Test that providing the Discord log-channel section requires a webhook URL.""" + with pytest.raises(ValidationError, match="Field required"): + SettingsSchema.model_validate( + _config(logging={"discord-channel": {"log-level": "ERROR"}}) + ) + + +class TestDurationParsing: + """Test case for parsing the delay/interval strings used by time-based settings.""" + + @staticmethod + @pytest.mark.parametrize( + ("raw_duration", "expected_duration"), + ( + ("30s", datetime.timedelta(seconds=30)), + ("10m", datetime.timedelta(minutes=10)), + ("24h", datetime.timedelta(hours=24)), + ("2d", datetime.timedelta(days=2)), + ("1h30m", datetime.timedelta(hours=1, minutes=30)), + ("90m", datetime.timedelta(minutes=90)), + ("1d12h30m15s", datetime.timedelta(days=1, hours=12, minutes=30, seconds=15)), + ("0.5h", datetime.timedelta(minutes=30)), + ("2w", datetime.timedelta(weeks=2)), + ("1w2d", datetime.timedelta(weeks=1, days=2)), + ("1H30M", datetime.timedelta(hours=1, minutes=30)), # NOTE: Capital letters + ("1h 30m", datetime.timedelta(hours=1, minutes=30)), # NOTE: Spaces + ), + ) + def test_valid_durations_are_parsed( + raw_duration: str, expected_duration: datetime.timedelta + ) -> None: + """Test that a duration written largest-unit-first is parsed.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": raw_duration}}) + ) + + assert settings.commands.strike.timeout_duration == expected_duration + + @staticmethod + @pytest.mark.parametrize( + "raw_duration", + ( + "30m1h", # NOTE: Units given smallest-first + "2d1w", # NOTE: Weeks given after days + "", # NOTE: An empty string is not a duration + "PT1H30M", # NOTE: An ISO-8601 duration + "01:30:00", + "5", # NOTE: No unit given + "5x", # NOTE: An unknown unit + "-1h", + ), + ) + def test_invalid_durations_are_rejected(raw_duration: str) -> None: + """Test that anything outside the documented duration format is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": raw_duration}}) + ) + + @staticmethod + @pytest.mark.parametrize( + "raw_duration", + ( + "9999999999w", + "999999999d24h", # NOTE: Each part fits, but their total does not + f"{'9' * 400}s", # NOTE: So many digits that it is read as infinity + ), + ) + def test_too_long_durations_are_rejected(raw_duration: str) -> None: + """ + Test that a duration too long to be held as a length of time is rejected. + + A setting with no upper limit of its own is used, so that the rejection can only + come from the duration parser itself. + """ + with pytest.raises(ValidationError, match="short enough to be held"): + SettingsSchema.model_validate( + _config(reminders={"send-introduction-reminders": {"delay": raw_duration}}) + ) + + @staticmethod + def test_an_already_parsed_duration_is_kept() -> None: + """ + Test that a value that is already a length of time is accepted unchanged. + + Each default value is re-validated whenever the model holding it is rebuilt, so + rejecting anything that is not a string would reject the schema's own defaults. + """ + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": datetime.timedelta(hours=3)}}) + ) + + assert settings.commands.strike.timeout_duration == datetime.timedelta(hours=3) + + +class TestZeroLengthDurations: + """Test case for durations of no length at all.""" + + @staticmethod + @pytest.mark.parametrize("raw_duration", ("0s", "0m", "0d0h0m0s", "0.0s")) + def test_a_zero_length_interval_is_rejected(raw_duration: str) -> None: + """ + Test that an interval of no length at all is rejected. + + Each interval becomes the loop period of a recurring task, so a zero-length one + would cause that task to run continuously without ever pausing. Rejecting only + the empty string is not enough, because `0s` is written deliberately. + """ + with pytest.raises(ValidationError, match="longer than zero"): + SettingsSchema.model_validate( + _config(reminders={"send-get-roles-reminders": {"interval": raw_duration}}) + ) + + @staticmethod + @pytest.mark.parametrize( + "raw_settings", + ( + { + "community-group": { + "links": {}, + "msl": {"auto-cookie-checking": {"interval": "0s"}}, + } + }, + {"reminders": {"send-introduction-reminders": {"interval": "0s"}}}, + {"reminders": {"send-get-roles-reminders": {"interval": "0s"}}}, + ), + ) + def test_every_task_interval_rejects_a_zero_length_duration( + raw_settings: Mapping[str, object], + ) -> None: + """Test that no recurring task can be configured to loop without pausing.""" + with pytest.raises(ValidationError, match="longer than zero"): + SettingsSchema.model_validate({**REQUIRED_SETTINGS, **raw_settings}) + + @staticmethod + def test_a_zero_length_delay_is_accepted() -> None: + """ + Test that waiting no time at all before sending a reminder is allowed. + + Unlike an interval, a delay of zero is a meaningful instruction: send the + reminder as soon as the member becomes eligible for it. + """ + settings: SettingsSchema = SettingsSchema.model_validate( + _config(reminders={"send-get-roles-reminders": {"delay": "0s"}}) + ) + + assert settings.reminders.send_get_roles_reminders.delay == datetime.timedelta(0) + + @staticmethod + def test_a_zero_length_strike_timeout_is_rejected() -> None: + """ + Test that timing a user out for no time at all is rejected. + + The duration is handed straight to Discord when the first strike is applied, so + a zero-length one would silently apply no moderation action whatsoever. + """ + with pytest.raises(ValidationError, match="longer than zero"): + SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": "0s"}}) + ) + + +class TestDiscordTimeoutLimit: + """Test case for the longest moderation timeout that Discord will apply.""" + + @staticmethod + @pytest.mark.parametrize( + ("raw_duration", "expected_duration"), + ( + ("1s", datetime.timedelta(seconds=1)), + ("28d", datetime.timedelta(days=28)), + ("27d23h59m59s", datetime.timedelta(days=27, hours=23, minutes=59, seconds=59)), + ), + ) + def test_a_duration_within_the_limit_is_accepted( + raw_duration: str, expected_duration: datetime.timedelta + ) -> None: + """Test that a timeout of 28 days or shorter is accepted, the limit included.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": raw_duration}}) + ) + + assert settings.commands.strike.timeout_duration == expected_duration + + @staticmethod + @pytest.mark.parametrize("raw_duration", ("28d0h0m1s", "29d", "365d")) + def test_a_duration_beyond_the_limit_is_rejected(raw_duration: str) -> None: + """ + Test that a timeout longer than 28 days is rejected. + + Discord refuses to disable a member's communication more than 28 days into the + future, & Pycord sends the request without checking, so a duration caught here + would otherwise fail only once a committee-member tried to apply a strike. + """ + with pytest.raises(ValidationError, match="no longer than 28 days"): + SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": raw_duration}}) + ) + + +class TestValueConstraints: + """Test case for the constraints applied to individual settings values.""" + + @staticmethod + @pytest.mark.parametrize("probability", (0, 0.5, 1)) + def test_easter_egg_probability_accepts_its_range(probability: float) -> None: + """Test that a probability within zero to one inclusive is accepted.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"ping": {"easter-egg-probability": probability}}) + ) + + assert settings.commands.ping.easter_egg_probability == probability + + @staticmethod + @pytest.mark.parametrize("probability", (-0.1, 1.1, 100)) + def test_easter_egg_probability_rejects_values_outside_its_range( + probability: float, + ) -> None: + """Test that a probability outside zero to one inclusive is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(commands={"ping": {"easter-egg-probability": probability}}) + ) + + @staticmethod + @pytest.mark.parametrize( + "full_name", + ("Computer Science Society", "St. John's Chess & Go Club", "Society #1: Hello!"), + ) + def test_group_full_name_accepts_plain_names(full_name: str) -> None: + """Test that a group name of letters, numbers & simple punctuation is accepted.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(**{"community-group": {"full-name": full_name}}) + ) + + assert settings.community_group.full_name == full_name + + @staticmethod + @pytest.mark.parametrize( + "full_name", + ("@everyone", "<@&1234567890123456789>", "**Bold** Society", "Société", "A" * 51), + ) + def test_group_full_name_rejects_mentions_and_formatting(full_name: str) -> None: + """ + Test that a group name which could ping or format a Discord message is rejected. + + The name is substituted into messages that TeX-Bot sends, so a name holding a + mention would ping whoever that mention names each time one of them is sent. + """ + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(**{"community-group": {"full-name": full_name}}) + ) + + @staticmethod + def test_a_discord_api_log_file_within_a_missing_folder_is_rejected( + tmp_path: Path, + ) -> None: + """ + Test that recording Discord API logs into a folder that does not exist is refused. + + Refusing it while validating is what stops a change naming such a file from being + written into the configuration file, & then failing as it is applied. + """ + with pytest.raises(ValidationError, match="does not exist"): + SettingsSchema.model_validate( + _config( + logging={ + "discord-api": { + "enabled": True, + "file-name": str(tmp_path / "missing" / "discord.log"), + } + } + ) + ) + + @staticmethod + def test_a_folder_is_rejected_as_the_discord_api_log_file(tmp_path: Path) -> None: + """Test that naming a folder as the Discord API log file is refused.""" + with pytest.raises(ValidationError, match="is a folder"): + SettingsSchema.model_validate( + _config(logging={"discord-api": {"enabled": True, "file-name": str(tmp_path)}}) + ) + + @staticmethod + def test_an_unusable_discord_api_log_file_is_allowed_while_disabled( + tmp_path: Path, + ) -> None: + """Test that the log file is only checked while Discord API logs are recorded.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config( + logging={ + "discord-api": { + "enabled": False, + "file-name": str(tmp_path / "missing" / "discord.log"), + } + } + ) + ) + + assert settings.logging.discord_api.enabled is False + + @staticmethod + @pytest.mark.parametrize("guild_id", (10**16 - 1, 10**20, 0, -1)) + def test_invalid_discord_snowflake_is_rejected(guild_id: int) -> None: + """Test that an ID outside the range of a Discord snowflake is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + { + **REQUIRED_SETTINGS, + "discord": {"bot-token": VALID_BOT_TOKEN, "main-guild-id": guild_id}, + } + ) + + @staticmethod + @pytest.mark.parametrize( + "bot_token", + ("", "not-a-token", "short.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs", VALID_BOT_TOKEN[:-1]), + ) + def test_invalid_bot_token_is_rejected(bot_token: str) -> None: + """Test that a value not matching the Discord bot-token format is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + { + **REQUIRED_SETTINGS, + "discord": {"bot-token": bot_token, "main-guild-id": VALID_MAIN_GUILD_ID}, + } + ) + + @staticmethod + @pytest.mark.parametrize( + "bot_token", + ( + "MTk4NjIyNDgzNDcxOTI1MjQ4.G_h-4y.ZnCjm1XVW7vRze4b7Cq4se7kKWs", + "MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se--kKWs", + "MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se__kKWs", + ), + ) + def test_bot_token_containing_punctuation_is_accepted(bot_token: str) -> None: + """ + Test that a token holding hyphens or underscores anywhere within it is accepted. + + Every segment of a Discord bot token is base64url-encoded, so any of them may + hold either character, & may hold two of them consecutively. The middle segment + (an encoded timestamp) routinely does. + """ + settings: SettingsSchema = SettingsSchema.model_validate( + { + **REQUIRED_SETTINGS, + "discord": {"bot-token": bot_token, "main-guild-id": VALID_MAIN_GUILD_ID}, + } + ) + + assert settings.discord.bot_token.get_secret_value() == bot_token + + @staticmethod + @pytest.mark.parametrize("lookback_days", (5, 1826)) + def test_statistics_lookback_accepts_its_range(lookback_days: int) -> None: + """Test that a lookback within five days to five years inclusive is accepted.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"stats": {"lookback-days": lookback_days}}) + ) + + assert settings.commands.stats.lookback_days == lookback_days + + @staticmethod + @pytest.mark.parametrize("lookback_days", (4, 1827, 0, -1)) + def test_statistics_lookback_rejects_values_outside_its_range(lookback_days: int) -> None: + """Test that a lookback outside five days to five years inclusive is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(commands={"stats": {"lookback-days": lookback_days}}) + ) + + @staticmethod + @pytest.mark.parametrize("organisation_id", ("123", "123456", "12a4", "", "1234 ")) + def test_invalid_msl_organisation_id_is_rejected(organisation_id: str) -> None: + """Test that an organisation ID that is not four or five digits is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config( + **{ + "community-group": { + "links": {}, + "msl": {"organisation-id": organisation_id}, + } + } + ) + ) + + @staticmethod + def test_an_unquoted_msl_organisation_id_is_accepted_as_text() -> None: + """Test that an organisation ID written without quotes is read as its digits.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(**{"community-group": {"links": {}, "msl": {"organisation-id": 1234}}}) + ) + + assert settings.community_group.msl.organisation_id == "1234" + + @staticmethod + @pytest.mark.parametrize("raw_organisation_id", ("01234", "1_234", "0x1234", "0o1234")) + def test_an_unquoted_msl_organisation_id_not_written_as_plain_digits_is_rejected( + raw_organisation_id: str, + ) -> None: + """ + Test that an unquoted organisation ID is rejected unless written as plain digits. + + YAML reads each of these as a number whose digits differ from those written, + so converting it to text would silently produce a different organisation ID. + """ + PARSED_ORGANISATION_ID: Final[object] = YAML().load(raw_organisation_id) + + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config( + **{ + "community-group": { + "links": {}, + "msl": {"organisation-id": PARSED_ORGANISATION_ID}, + } + } + ) + ) + + @staticmethod + @pytest.mark.parametrize( + ("setting_name", "value_with_trailing_newline"), + (("organisation-id", "1234\n"), ("auth-cookie", f"{'a' * 512}\n")), + ) + def test_a_trailing_newline_does_not_satisfy_a_pattern( + setting_name: str, value_with_trailing_newline: str + ) -> None: + r""" + Test that a value is not accepted merely because its first line would be. + + Every pattern is anchored with `\Z` rather than `$`, so that a trailing newline + cannot smuggle an otherwise-rejected value through. This is why the schema uses + Python's regular-expression engine, rather than the Rust engine Pydantic + defaults to, which does not support that anchor. + """ + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config( + **{ + "community-group": { + "links": {}, + "msl": {setting_name: value_with_trailing_newline}, + } + } + ) + ) + + @staticmethod + def test_non_discord_webhook_url_is_rejected() -> None: + """Test that a URL that is not a Discord webhook is rejected.""" + with pytest.raises(ValidationError, match="Discord webhook URL"): + SettingsSchema.model_validate( + _config(logging={"discord-channel": {"webhook-url": "https://example.com"}}) + ) + + @staticmethod + def test_discord_webhook_url_is_accepted() -> None: + """Test that a Discord webhook URL is accepted.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(logging={"discord-channel": {"webhook-url": VALID_WEBHOOK_URL}}) + ) + + assert settings.logging.discord_channel is not None + assert str(settings.logging.discord_channel.webhook_url).startswith( + "https://discord.com/api/webhooks/" + ) + + @staticmethod + def test_a_sequence_of_distinct_values_is_accepted() -> None: + """Test that a list of role names holding no repetitions is kept as written.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config( + **{ + "community-group": { + "links": {}, + "msl": {}, + "membership-dependent-roles": ["Member", "Committee"], + } + } + ) + ) + + assert settings.community_group.membership_dependent_roles == ("Member", "Committee") + + @staticmethod + def test_duplicate_values_within_a_unique_sequence_are_rejected() -> None: + """Test that repeating a value within a set of role names is rejected.""" + with pytest.raises(ValidationError, match="unique"): + SettingsSchema.model_validate( + _config(commands={"stats": {"displayed-roles": ["Member", "Member"]}}) + ) + + +class TestValueNormalisation: + """Test case for values that are accepted in more than one form.""" + + @staticmethod + @pytest.mark.parametrize( + "raw_log_level", ("DEBUG", "debug", " Debug ", "-debug-", "debug.") + ) + def test_log_level_is_matched_case_and_punctuation_agnostically( + raw_log_level: str, + ) -> None: + """Test that a log level is recognised regardless of case or stray punctuation.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(logging={"console": {"log-level": raw_log_level}}) + ) + + assert settings.logging.console.log_level == LogLevel.DEBUG + + @staticmethod + def test_unknown_log_level_is_rejected() -> None: + """Test that a value that is not a log level is rejected.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(logging={"console": {"log-level": "NONSENSE"}}) + ) + + @staticmethod + @pytest.mark.parametrize( + ("raw_flag", "expected_flag"), + ( + ("once", "once"), + ("interval", "interval"), + (True, "once"), + ("true", "once"), + ("yes", "once"), + ("on", "once"), + ("1", "once"), + (" Once ", "once"), + (False, False), + ("false", False), + ("no", False), + ("off", False), + ("0", False), + ), + ) + def test_send_introduction_reminders_flag_is_normalised( + raw_flag: object, expected_flag: object + ) -> None: + """Test that boolean-like values are treated as their canonical equivalent.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(reminders={"send-introduction-reminders": {"enabled": raw_flag}}) + ) + + assert settings.reminders.send_introduction_reminders.enabled == expected_flag + + @staticmethod + @pytest.mark.parametrize("raw_flag", ("maybe", "sometimes", "ONCE-ish")) + def test_an_unrecognised_reminders_flag_string_is_rejected(raw_flag: str) -> None: + """Test that a string outside the recognised options is not quietly accepted.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(reminders={"send-introduction-reminders": {"enabled": raw_flag}}) + ) + + @staticmethod + def test_lookback_days_is_exposed_as_a_period() -> None: + """Test that the statistics lookback is usable as a length of time.""" + settings: SettingsSchema = SettingsSchema.model_validate( + _config(commands={"stats": {"lookback-days": 14}}) + ) + + assert settings.commands.stats.lookback_period == datetime.timedelta(days=14) + + +class TestSecrecy: + """Test case for keeping secret settings out of logs & error messages.""" + + @staticmethod + def test_secret_values_are_masked_when_displayed() -> None: + """Test that a secret value is not revealed by displaying the settings.""" + settings: SettingsSchema = SettingsSchema.model_validate(_config()) + + assert VALID_BOT_TOKEN not in repr(settings) + assert VALID_BOT_TOKEN not in str(settings.discord.bot_token) + + @staticmethod + def test_secret_values_remain_readable_when_explicitly_requested() -> None: + """Test that a secret value can still be read where it is genuinely needed.""" + settings: SettingsSchema = SettingsSchema.model_validate(_config()) + + assert settings.discord.bot_token.get_secret_value() == VALID_BOT_TOKEN + + @staticmethod + def test_rejected_secret_value_is_absent_from_scrubbed_errors() -> None: + """Test that an invalid secret is not echoed back by a scrubbed error message.""" + invalid_token: Final[str] = "SUPER-SECRET-BUT-INVALID" # noqa: S105 + + with pytest.raises(ValidationError) as validation_error: + SettingsSchema.model_validate( + { + **REQUIRED_SETTINGS, + "discord": { + "bot-token": invalid_token, + "main-guild-id": VALID_MAIN_GUILD_ID, + }, + } + ) + + assert invalid_token not in str( + validation_error.value.errors(include_input=False, include_url=False) + ) + + +class TestSettingsMetadata: + """Test case for the metadata describing each setting to a human.""" + + @staticmethod + def test_every_setting_is_described() -> None: + """Test that no setting is missing its help text.""" + undescribed_settings: Sequence[str] = [ + settings_name + for settings_name, metadata in get_settings_metadata().items() + if not metadata.description + ] + + assert not undescribed_settings + + @staticmethod + def test_settings_requiring_a_restart_are_exactly_those_that_cannot_be_applied() -> None: + """ + Test that only the settings which genuinely cannot be applied need a restart. + + Flagging a setting that could be applied would send committee members away to + restart TeX-Bot for no reason, and failing to flag one that cannot would leave + them believing a change had taken effect when it had not. + """ + EXPECTED_RESTART_REQUIRED_SETTINGS: Final[frozenset[str]] = frozenset( + { + # NOTE: Used to connect to Discord & to populate the shortcut accessors. + "discord:bot-token", + "discord:main-guild-id", + # NOTE: Baked into the names & descriptions of the slash commands that + # refer to your group, & so fixed when those commands are registered. + "community-group:full-name", + "community-group:short-name", + # NOTE: Fixed when each recurring task is created during start-up. + "community-group:msl:auto-cookie-checking:enabled", + "community-group:msl:auto-cookie-checking:interval", + "reminders:send-introduction-reminders:enabled", + "reminders:send-introduction-reminders:interval", + "reminders:send-get-roles-reminders:enabled", + "reminders:send-get-roles-reminders:interval", + } + ) + + assert ( + frozenset( + settings_name + for settings_name, metadata in get_settings_metadata().items() + if metadata.requires_restart + ) + == EXPECTED_RESTART_REQUIRED_SETTINGS + ) + + @staticmethod + def test_delays_do_not_require_a_restart() -> None: + """ + Test that the delay before a reminder is sent takes effect without a restart. + + Unlike the interval of the task that sends them, a delay is read from the + settings accessor at the moment it is used. + """ + SETTINGS_METADATA: Final[Mapping[str, ConfigSettingMetadata]] = get_settings_metadata() + + assert not SETTINGS_METADATA[ + "reminders:send-introduction-reminders:delay" + ].requires_restart + assert not SETTINGS_METADATA[ + "reminders:send-get-roles-reminders:delay" + ].requires_restart + + @staticmethod + def test_every_secret_setting_is_flagged() -> None: + """Test that each setting holding a credential is marked as secret.""" + EXPECTED_SECRET_SETTINGS: Final[frozenset[str]] = frozenset( + { + "discord:bot-token", + "community-group:msl:auth-cookie", + "logging:discord-channel:webhook-url", + } + ) + + assert ( + frozenset( + settings_name + for settings_name, metadata in get_settings_metadata().items() + if metadata.secret + ) + == EXPECTED_SECRET_SETTINGS + ) + + @staticmethod + def test_only_settings_an_optional_section_needs_are_flagged_as_such() -> None: + """ + Test that each setting an optional section cannot be used without names it. + + Removing such a setting removes the whole of that section with it, so flagging any + other setting would remove settings that whoever removed it never asked to remove. + """ + assert { + settings_name: metadata.required_by_optional_section + for settings_name, metadata in get_settings_metadata().items() + if metadata.required_by_optional_section is not None + } == {"logging:discord-channel:webhook-url": "logging:discord-channel"} + + @staticmethod + def test_metadata_covers_every_configurable_setting() -> None: + """Test that the metadata describes exactly the settings that can be configured.""" + from config._accessor import flatten_settings # noqa: PLC0415 + + SETTINGS_NAMES: Final[frozenset[str]] = frozenset( + flatten_settings(SettingsSchema.model_validate(_config())) + ) + + # NOTE: Every flattened key path must name a setting that `/config` recognises, + # including those within an optional section that has been omitted entirely. + assert not SETTINGS_NAMES - frozenset(get_settings_metadata()) + assert not frozenset(get_settings_metadata()) - SETTINGS_NAMES + + +def test_minimal_config_fixture_matches_the_required_settings() -> None: + """Test that the shared minimal configuration holds exactly what the schema requires.""" + assert "bot-token" in MINIMAL_CONFIG + assert "main-guild-id" in MINIMAL_CONFIG + + +class TestNonStringValues: + """Test case for values given as the wrong type entirely.""" + + @staticmethod + @pytest.mark.parametrize("raw_duration", (30, 1.5, True, None, ["1h"])) + def test_a_duration_that_is_not_a_string_is_rejected(raw_duration: object) -> None: + """Test that a duration must be written as a string, not a bare number.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(commands={"strike": {"timeout-duration": raw_duration}}) + ) + + @staticmethod + @pytest.mark.parametrize("raw_log_level", (10, None, ["DEBUG"])) + def test_a_log_level_that_is_not_a_string_is_rejected(raw_log_level: object) -> None: + """Test that a log level must be written as one of its names.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(logging={"console": {"log-level": raw_log_level}}) + ) + + @staticmethod + @pytest.mark.parametrize("raw_flag", (42, None, ["once"], 0, 1)) + def test_an_unrecognised_reminders_flag_is_rejected(raw_flag: object) -> None: + """ + Test that a send-introduction-reminders value outside its options is rejected. + + `0` is included because Pydantic would otherwise accept it as `False` while + rejecting the `1` its author would pair it with, silently disabling introduction + reminders for anyone who wrote them as numbers. + """ + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(reminders={"send-introduction-reminders": {"enabled": raw_flag}}) + ) + + @staticmethod + def test_a_webhook_url_that_is_not_a_url_is_rejected() -> None: + """Test that the Discord log-channel webhook must be a URL.""" + with pytest.raises(ValidationError): + SettingsSchema.model_validate( + _config(logging={"discord-channel": {"webhook-url": 42}}) + ) diff --git a/tests/test_msl.py b/tests/test_msl.py new file mode 100644 index 000000000..d101ca035 --- /dev/null +++ b/tests/test_msl.py @@ -0,0 +1,332 @@ +"""Test suite for the features that depend upon your group's MSL website.""" + +__all__: Sequence[str] = ( + "TestCheckMSLAuthCookieIsSet", + "TestCheckMSLIsConfigured", + "TestMembershipListCache", + "TestSUPlatformAccessCookieCheckTask", +) + +import asyncio +lazy from collections.abc import Awaitable, Callable, Sequence +lazy from pathlib import Path +lazy from typing import Final + +import pytest +lazy from discord.ext.commands.errors import CheckAnyFailure + +import config +from config._accessor import SettingsAccessor +from utils import CommandChecks +lazy from cogs.check_su_platform_authorisation import ( + CheckSUPlatformAuthorisationTaskCog, + SUPlatformAccessCookieStatus, +) +lazy from utils import TeXBotBaseCog +lazy from utils.msl import is_id_a_community_group_member + +type MSLSettingsApplier = Callable[[str | None, str | None], None] + +# NOTE: A fabricated value, structured to satisfy the bot-token pattern: +# 24-26 characters, then 6, then 27-38. +VALID_BOT_TOKEN: Final[str] = "MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs" # noqa: S105 + +VALID_MAIN_GUILD_ID: Final[int] = 1234567890123456789 + +VALID_ORGANISATION_ID: Final[str] = "1234" + +VALID_AUTH_COOKIE: Final[str] = "a" * 600 + +REQUIRED_SETTINGS_YAML: Final[str] = ( + f"discord:\n bot-token: {VALID_BOT_TOKEN}\n main-guild-id: {VALID_MAIN_GUILD_ID}\n" +) + + +def _settings_yaml(organisation_id: str | None, auth_cookie: str | None) -> str: + """Return a valid configuration holding only the given MSL settings.""" + msl_settings_yaml: str = "".join( + f" {setting_name}: '{setting_value}'\n" + for setting_name, setting_value in ( + ("organisation-id", organisation_id), + ("auth-cookie", auth_cookie), + ) + if setting_value is not None + ) + + if not msl_settings_yaml: + return REQUIRED_SETTINGS_YAML + + return f"{REQUIRED_SETTINGS_YAML}community-group:\n msl:\n{msl_settings_yaml}" + + +@pytest.fixture(scope="module", autouse=True) +def _load_required_settings(tmp_path_factory: pytest.TempPathFactory) -> None: + """ + Load a valid configuration before any cog is imported. + + Importing any cog loads every other one alongside it, several of which read the + configuration as they are imported, so a valid configuration must already be loaded + before the import can succeed at all. + """ + CONFIG_FILE_PATH: Final[Path] = tmp_path_factory.mktemp("msl") / "tex-bot-deployment.yaml" + CONFIG_FILE_PATH.write_text(REQUIRED_SETTINGS_YAML, encoding="utf-8") + + config.settings.reload(CONFIG_FILE_PATH) + + +@pytest.fixture() +def apply_msl_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> MSLSettingsApplier: + """Return a callable that loads a configuration holding only the given MSL settings.""" + + def _apply_msl_settings(organisation_id: str | None, auth_cookie: str | None) -> None: + config_file_path: Path = tmp_path / "tex-bot-deployment.yaml" + config_file_path.write_text( + _settings_yaml(organisation_id, auth_cookie), encoding="utf-8" + ) + + settings_accessor: SettingsAccessor = SettingsAccessor() + settings_accessor.reload(config_file_path) + + monkeypatch.setattr("utils.msl.memberships.settings", settings_accessor) + + return _apply_msl_settings + + +PARTIAL_MSL_SETTINGS: Final[Sequence[tuple[str | None, str | None]]] = ( + (None, None), + (VALID_ORGANISATION_ID, None), + (None, VALID_AUTH_COOKIE), +) + + +class TestCheckMSLIsConfigured: + """Test case for the command check that requires both MSL settings to be set.""" + + @staticmethod + def _run_check() -> Awaitable[bool]: + """Run the MSL command check, as it would be run before a command is executed.""" + + @CommandChecks.check_msl_is_configured + async def _command(_cog: TeXBotBaseCog) -> None: + pass + + MSL_CHECK: Final[Callable[[object], Awaitable[bool]]] = _command.__commands_checks__[0] # type: ignore[attr-defined] + + return MSL_CHECK(None) + + @classmethod + @pytest.mark.parametrize(("organisation_id", "auth_cookie"), PARTIAL_MSL_SETTINGS) + def test_a_command_is_refused_without_both_msl_settings( + cls, + apply_msl_settings: MSLSettingsApplier, + organisation_id: str | None, + auth_cookie: str | None, + ) -> None: + """Test that a partial MSL configuration is still valid, but stops the command.""" + apply_msl_settings(organisation_id, auth_cookie) + + with pytest.raises(CheckAnyFailure) as check_failure: + asyncio.run(cls._run_check()) + + assert CommandChecks.is_msl_is_configured_failure(check_failure.value.checks[0]) # type: ignore[arg-type] + + @classmethod + def test_a_command_runs_with_both_msl_settings( + cls, apply_msl_settings: MSLSettingsApplier + ) -> None: + """Test that setting both the organisation ID & cookie lets the command run.""" + apply_msl_settings(VALID_ORGANISATION_ID, VALID_AUTH_COOKIE) + + assert asyncio.run(cls._run_check()) is True + + +class TestCheckMSLAuthCookieIsSet: + """Test case for the command check that requires only the MSL cookie to be set.""" + + @staticmethod + def _run_check() -> Awaitable[bool]: + """Run the MSL cookie command check, as it would be run before a command.""" + + @CommandChecks.check_msl_auth_cookie_is_set + async def _command(_cog: TeXBotBaseCog) -> None: + pass + + MSL_AUTH_COOKIE_CHECK: Final[Callable[[object], Awaitable[bool]]] = ( + _command.__commands_checks__[0] # type: ignore[attr-defined] + ) + + return MSL_AUTH_COOKIE_CHECK(None) + + @classmethod + @pytest.mark.parametrize("organisation_id", (None, VALID_ORGANISATION_ID)) + def test_a_command_is_refused_without_the_cookie( + cls, apply_msl_settings: MSLSettingsApplier, organisation_id: str | None + ) -> None: + """Test that a command needing only the cookie is stopped when it is not set.""" + apply_msl_settings(organisation_id, None) + + with pytest.raises(CheckAnyFailure) as check_failure: + asyncio.run(cls._run_check()) + + assert CommandChecks.is_msl_auth_cookie_is_set_failure( + check_failure.value.checks[0] # type: ignore[arg-type] + ) + + @classmethod + def test_a_command_runs_with_only_the_cookie( + cls, apply_msl_settings: MSLSettingsApplier + ) -> None: + """ + Test that a command needing only the cookie runs without an organisation ID. + + Listing the organisations the cookie can reach is how the organisation ID is + found, so requiring that ID first would block the way to finding it. + """ + apply_msl_settings(None, VALID_AUTH_COOKIE) + + assert asyncio.run(cls._run_check()) is True + + +@pytest.fixture() +def cookie_status_requests(monkeypatch: pytest.MonkeyPatch) -> list[None]: + """Return a record of each time the cookie check task asks the SU platform for status.""" + status_requests: list[None] = [] + + async def _get_su_platform_access_cookie_status( + _cog: CheckSUPlatformAuthorisationTaskCog, + ) -> SUPlatformAccessCookieStatus: + status_requests.append(None) + return SUPlatformAccessCookieStatus.AUTHORISED + + monkeypatch.setattr( + CheckSUPlatformAuthorisationTaskCog, + "get_su_platform_access_cookie_status", + _get_su_platform_access_cookie_status, + ) + + return status_requests + + +def _run_cookie_check_task() -> None: + """Run a single iteration of the SU platform access cookie check task.""" + # NOTE: The task's own constructor would start the repeating task, so the cog is + # created without it. The task never reaches for the running bot before the request + # that is being recorded, so it does not need a connection to Discord. + cog: CheckSUPlatformAuthorisationTaskCog = CheckSUPlatformAuthorisationTaskCog.__new__( + CheckSUPlatformAuthorisationTaskCog + ) + + asyncio.run( + CheckSUPlatformAuthorisationTaskCog.su_platform_access_cookie_check_task.coro(cog) + ) + + +class TestSUPlatformAccessCookieCheckTask: + """Test case for the repeated task that checks the SU platform access cookie.""" + + @staticmethod + @pytest.mark.parametrize(("organisation_id", "auth_cookie"), PARTIAL_MSL_SETTINGS) + def test_the_check_is_skipped_without_both_msl_settings( + apply_msl_settings: MSLSettingsApplier, + cookie_status_requests: list[None], + organisation_id: str | None, + auth_cookie: str | None, + ) -> None: + """Test that the task neither fails nor contacts the SU platform when not set up.""" + apply_msl_settings(organisation_id, auth_cookie) + + _run_cookie_check_task() + + assert not cookie_status_requests + + @staticmethod + def test_the_check_runs_with_both_msl_settings( + apply_msl_settings: MSLSettingsApplier, cookie_status_requests: list[None] + ) -> None: + """Test that the task checks the cookie once both MSL settings are set.""" + apply_msl_settings(VALID_ORGANISATION_ID, VALID_AUTH_COOKIE) + + _run_cookie_check_task() + + assert len(cookie_status_requests) == 1 + + +CACHED_MEMBER_ID: Final[int] = 1234567 + + +@pytest.fixture() +def members_list_fetches(monkeypatch: pytest.MonkeyPatch) -> list[None]: + """Return a record of each time the members-list is fetched from the MSL website.""" + fetches: list[None] = [] + + async def _fetch_community_group_members_list() -> set[int]: + fetches.append(None) + return set() + + monkeypatch.setattr( + "utils.msl.memberships.fetch_community_group_members_list", + _fetch_community_group_members_list, + ) + + return fetches + + +@pytest.fixture() +def cache_members_list(monkeypatch: pytest.MonkeyPatch) -> Callable[[str], None]: + """Return a callable filling the members-list cache as fetched for an organisation.""" + + def _cache_members_list(organisation_id: str) -> None: + monkeypatch.setattr("utils.msl.memberships._membership_list_cache", {CACHED_MEMBER_ID}) + monkeypatch.setattr( + "utils.msl.memberships._membership_list_cache_organisation_id", organisation_id + ) + + return _cache_members_list + + +class TestMembershipListCache: + """Test case for reusing the members-list most recently fetched from MSL.""" + + @staticmethod + def test_a_cached_member_is_accepted_without_fetching_again( + apply_msl_settings: MSLSettingsApplier, + cache_members_list: Callable[[str], None], + members_list_fetches: list[None], + ) -> None: + """Test that a member already within the cached members-list is accepted at once.""" + apply_msl_settings(VALID_ORGANISATION_ID, VALID_AUTH_COOKIE) + cache_members_list(VALID_ORGANISATION_ID) + + assert asyncio.run(is_id_a_community_group_member(CACHED_MEMBER_ID)) is True + assert not members_list_fetches + + @staticmethod + def test_changing_the_organisation_id_clears_the_cache( + apply_msl_settings: MSLSettingsApplier, + cache_members_list: Callable[[str], None], + members_list_fetches: list[None], + ) -> None: + """ + Test that a members-list fetched for one organisation is not used for another. + + Otherwise, correcting a mistyped organisation ID would leave the members of + whichever organisation it named able to use `/make-member`. + """ + apply_msl_settings("5678", VALID_AUTH_COOKIE) + cache_members_list(VALID_ORGANISATION_ID) + + assert asyncio.run(is_id_a_community_group_member(CACHED_MEMBER_ID)) is False + assert len(members_list_fetches) == 1 + + @staticmethod + def test_changing_only_the_cookie_keeps_the_cache( + apply_msl_settings: MSLSettingsApplier, + cache_members_list: Callable[[str], None], + members_list_fetches: list[None], + ) -> None: + """Test that replacing an expired cookie does not throw away the members-list.""" + apply_msl_settings(VALID_ORGANISATION_ID, "b" * 600) + cache_members_list(VALID_ORGANISATION_ID) + + assert asyncio.run(is_id_a_community_group_member(CACHED_MEMBER_ID)) is True + assert not members_list_fetches diff --git a/tests/test_strike.py b/tests/test_strike.py new file mode 100644 index 000000000..81a2570f1 --- /dev/null +++ b/tests/test_strike.py @@ -0,0 +1,95 @@ +"""Test suite for the strike commands.""" + +__all__: Sequence[str] = ("TestReportedMessageDestination",) + +import asyncio +lazy from collections.abc import Sequence +lazy from pathlib import Path +lazy from types import SimpleNamespace +lazy from typing import Final, cast + +import pytest +lazy import discord + +import config +from config._accessor import SettingsAccessor +lazy from cogs.strike import StrikeContextCommandsCog +lazy from utils import TeXBot, TeXBotApplicationContext + +# NOTE: A fabricated value, structured to satisfy the bot-token pattern: +# 24-26 characters, then 6, then 27-38. +VALID_BOT_TOKEN: Final[str] = "MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs" # noqa: S105 + +REQUIRED_SETTINGS_YAML: Final[str] = ( + f"discord:\n bot-token: {VALID_BOT_TOKEN}\n main-guild-id: 1234567890123456789\n" +) + + +@pytest.fixture(scope="module", autouse=True) +def _load_required_settings(tmp_path_factory: pytest.TempPathFactory) -> None: + """ + Load a valid configuration before any cog is imported. + + Importing any cog loads every other one alongside it, several of which read the + configuration as they are imported, so a valid configuration must already be loaded + before the import can succeed at all. + """ + CONFIG_FILE_PATH: Final[Path] = tmp_path_factory.mktemp("strike") / "tex-bot.yaml" + CONFIG_FILE_PATH.write_text(REQUIRED_SETTINGS_YAML, encoding="utf-8") + + config.settings.reload(CONFIG_FILE_PATH) + + +class TestReportedMessageDestination: + """Test case for the channel that reported messages are sent to.""" + + @staticmethod + def test_the_configured_channel_is_used( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """ + Test that a reported message is sent to the channel named within the settings. + + A "#discord" channel exists but is not the one configured, so finding it instead + would mean the setting had been ignored. + """ + CONFIG_FILE_PATH: Final[Path] = tmp_path / "tex-bot.yaml" + CONFIG_FILE_PATH.write_text( + f"{REQUIRED_SETTINGS_YAML}" + "commands:\n" + " strike:\n" + " reported-message-destination-channel: mod-reports\n", + encoding="utf-8", + ) + settings_accessor: SettingsAccessor = SettingsAccessor() + settings_accessor.reload(CONFIG_FILE_PATH) + monkeypatch.setattr("cogs.strike.settings", settings_accessor) + + # NOTE: The cog is created without its constructor, & given a stand-in for the + # running bot, so that no connection to Discord is needed. + cog: StrikeContextCommandsCog = StrikeContextCommandsCog.__new__( + StrikeContextCommandsCog + ) + cog.bot = cast( + "TeXBot", + SimpleNamespace( + main_guild=SimpleNamespace(text_channels=[SimpleNamespace(name="discord")]) + ), + ) + + error_messages: list[str] = [] + + async def _command_send_error(_ctx: object, message: str) -> None: + error_messages.append(message) + + monkeypatch.setattr(cog, "command_send_error", _command_send_error) + + asyncio.run( + cog._send_message_to_committee( # noqa: SLF001 + cast("TeXBotApplicationContext", None), cast("discord.Message", None) + ) + ) + + assert error_messages == [ + "Could not find the `#mod-reports` channel in the main guild!" + ] diff --git a/tex-bot-deployment.example.yaml b/tex-bot-deployment.example.yaml new file mode 100644 index 000000000..b4c11357b --- /dev/null +++ b/tex-bot-deployment.example.yaml @@ -0,0 +1,141 @@ +# An example TeX-Bot deployment configuration file. +# +# Copy this file to `tex-bot-deployment.yaml` and fill in the required values. +# (Set the `TEX_BOT_CONFIG_PATH` environment variable to keep it somewhere else.) +# +# Every comment & blank line in this file is removed whenever TeX-Bot rewrites it +# (when the `/config set` or `/config unset` command is used), & the file is written +# in a standard layout. Keep a copy elsewhere of any notes you want to keep. +# Each setting's description can be seen with `/config get`. +# +# Durations are written largest-unit-first, in the format +# `wdhms`, so `1h30m`, `2d` and `1w` are all +# valid. Capital letters & spaces are ignored, so `1H 30M` is also valid. +# Every part must carry its unit, so a bare `24` is rejected rather than being read as +# 24 seconds. The `interval` of a recurring task must be longer than zero, because a +# task set to repeat every `0s` would run continuously without ever pausing; the same +# applies to the strike `timeout-duration`, because a `0s` timeout would apply no +# moderation action at all. +# +# Run `/config reload` after editing this file to apply your changes. +# +# Individual settings can also be changed from within Discord, without editing this file +# by hand: `/config get` shows what a setting is currently set to, `/config set` changes +# one, and `/config unset` returns one to its default. Each of them is committee-only. +# `/config set` & `/config unset` write back to this file without any of its comments. +# +# If you edit this file by hand, run `/config reload` before using `/config set` or +# `/config unset`. Both refuse to run against a file whose settings have been edited +# since TeX-Bot last loaded it, so that a change made from within Discord is never +# quietly mixed together with one made here. Editing only the comments does not count. +# Most settings take effect straight away, because they are read at the moment they +# are used. A few cannot, and `/config reload` will tell you when a restart is needed: +# +# * `discord:bot-token` & `discord:main-guild-id` are used to connect to Discord and +# to look up your guild's roles & channels while TeX-Bot is starting up. +# * `community-group:full-name` & `community-group:short-name` are used within the +# names & descriptions of some commands (`/make-member` & `/stats`), which are +# given to Discord while TeX-Bot is starting up. +# * The `enabled` & `interval` of any recurring task (the reminders below, and MSL +# auto-cookie-checking) are fixed when that task is created at start-up. Their +# `delay` settings are *not*, and do take effect immediately. +# +# A reload never applies a configuration that fails validation: if this file contains a +# mistake, TeX-Bot keeps running on the last configuration that loaded successfully and +# reports the line responsible. + +discord: + # REQUIRED. From your bot's page within the Discord developer portal: + # + bot-token: "" + # REQUIRED. The ID of your community group's main Discord guild. + main-guild-id: 0 + +# Everything below is optional, & may be left out entirely. Each value shown is the +# default that TeX-Bot uses when the setting is not written here at all. +# +# An empty value is not the same as an absent one: every setting that is present must +# hold a valid value, so leave a setting out entirely rather than setting it to "". + +community-group: + # Falls back to the name of your Discord guild. + # full-name: Computer Science Society + # Falls back to being derived from the full name. + # short-name: CSS + # Roles that should only be held by members of your community group. + membership-dependent-roles: [] + + # Uncomment only the links you have; each one is used solely by the messages that + # mention it, which leave it out when it is unset. + # links: + # purchase-membership: https://example.com/join + # membership-perks: https://example.com/perks + # moderation-policy: https://example.com/moderation-policy + # # Used in place of an invite link generated by TeX-Bot. + # custom-discord-invite-link: https://discord.gg/example + + msl: + # Your community group's organisation ID on your MSL website. + # organisation-id: "1234" + # Your members-list authentication session cookie, extracted from your + # web-browser after logging in. It is probably named `.AspNet.SharedCookie`. + # auth-cookie: your-authentication-cookie-value + auto-cookie-checking: + enabled: false + interval: 10m + +logging: + console: + log-level: INFO + # Omit this section entirely to disable Discord log-channel logging. + # discord-channel: + # webhook-url: https://discord.com/api/webhooks/... + # log-level: WARNING + discord-api: + enabled: false + log-level: INFO + # The folder holding this file must already exist. + file-name: discord.log + +commands: + ping: + easter-egg-probability: 0.01 + stats: + lookback-days: 30 + displayed-roles: + - Committee + - Committee-Elect + - Student Rep + - Member + - Guest + - Server Booster + - Foundation Year + - First Year + - Second Year + - Final Year + - Year In Industry + - Year Abroad + - PGT + - PGR + - Alumnus/Alumna + - Postdoc + - Quiz Victor + strike: + performed-manually-warning-location: DM + # How long a first strike times a member out for. + # Discord will not apply a timeout longer than 28 days. + timeout-duration: 1d + reported-message-destination-channel: discord + +reminders: + send-introduction-reminders: + # One of `once`, `interval` or `false`. + enabled: once + delay: 1d16h + interval: 6h + send-get-roles-reminders: + enabled: true + delay: 1d16h + interval: 1d + +auto-add-committee-to-threads: true diff --git a/utils/command_checks.py b/utils/command_checks.py index 3f0307658..bc29f65b5 100644 --- a/utils/command_checks.py +++ b/utils/command_checks.py @@ -10,6 +10,7 @@ lazy from exceptions import DiscordMemberNotInMainGuildError +lazy from .msl import msl_auth_cookie_is_set, msl_is_configured lazy from .tex_bot_base_cog import TeXBotBaseCog lazy from .tex_bot_contexts import TeXBotApplicationContext @@ -65,6 +66,50 @@ async def check_interaction_user_has_committee_role( ) )(func) + @staticmethod + def check_msl_is_configured[T: TeXBotBaseCog, **P]( + func: Callable[Concatenate[T, P], Awaitable[None]], + ) -> Callable[Concatenate[T, P], Awaitable[None]]: + """ + Command check decorator to ensure that your group's MSL website can be accessed. + + Both the MSL organisation ID & the MSL authentication cookie must be set. + If this check does not pass, the decorated command will not be executed. + Instead, an error message will be sent to the user. + """ + + # NOTE: The check function shares this decorator's name, so that `is_msl_is_configured_failure()` can identify it within a `CheckAnyFailure` + async def check_msl_is_configured(ctx: TeXBotApplicationContext) -> bool: # noqa: ARG001 + return msl_is_configured() + + return commands.check_any( + commands.check( + check_msl_is_configured # type: ignore[arg-type] + ) + )(func) + + @staticmethod + def check_msl_auth_cookie_is_set[T: TeXBotBaseCog, **P]( + func: Callable[Concatenate[T, P], Awaitable[None]], + ) -> Callable[Concatenate[T, P], Awaitable[None]]: + """ + Command check decorator to ensure that the SU platform access cookie is set. + + For commands that reach the SU platform without needing your group's MSL + organisation ID. If this check does not pass, the decorated command will not be + executed. Instead, an error message will be sent to the user. + """ + + # NOTE: The check function shares this decorator's name, so that `is_msl_auth_cookie_is_set_failure()` can identify it within a `CheckAnyFailure` + async def check_msl_auth_cookie_is_set(ctx: TeXBotApplicationContext) -> bool: # noqa: ARG001 + return msl_auth_cookie_is_set() + + return commands.check_any( + commands.check( + check_msl_auth_cookie_is_set # type: ignore[arg-type] + ) + )(func) + @classmethod def is_interaction_user_in_main_guild_failure(cls, check: CheckFailure) -> bool: """Whether the check failed due to the user not being in your Discord guild.""" @@ -74,3 +119,13 @@ def is_interaction_user_in_main_guild_failure(cls, check: CheckFailure) -> bool: def is_interaction_user_has_committee_role_failure(cls, check: CheckFailure) -> bool: """Whether the check failed due to the user not having the committee role.""" return bool(check.__name__ == cls.check_interaction_user_has_committee_role.__name__) # type: ignore[attr-defined] + + @classmethod + def is_msl_is_configured_failure(cls, check: CheckFailure) -> bool: + """Whether the check failed due to your group's MSL website not being set up.""" + return bool(check.__name__ == cls.check_msl_is_configured.__name__) # type: ignore[attr-defined] + + @classmethod + def is_msl_auth_cookie_is_set_failure(cls, check: CheckFailure) -> bool: + """Whether the check failed due to the SU platform access cookie not being set.""" + return bool(check.__name__ == cls.check_msl_auth_cookie_is_set.__name__) # type: ignore[attr-defined] diff --git a/utils/msl/__init__.py b/utils/msl/__init__.py index 7882587f9..066bcc75c 100644 --- a/utils/msl/__init__.py +++ b/utils/msl/__init__.py @@ -5,6 +5,8 @@ "fetch_community_group_members_list", "fetch_url_content_with_session", "is_id_a_community_group_member", + "msl_auth_cookie_is_set", + "msl_is_configured", ) lazy from collections.abc import Sequence @@ -14,4 +16,6 @@ fetch_community_group_members_list, fetch_url_content_with_session, is_id_a_community_group_member, + msl_auth_cookie_is_set, + msl_is_configured, ) diff --git a/utils/msl/memberships.py b/utils/msl/memberships.py index 519ba1bf5..c2c050336 100644 --- a/utils/msl/memberships.py +++ b/utils/msl/memberships.py @@ -5,6 +5,8 @@ "fetch_community_group_members_list", "fetch_url_content_with_session", "is_id_a_community_group_member", + "msl_auth_cookie_is_set", + "msl_is_configured", ) import logging @@ -17,6 +19,7 @@ lazy import aiohttp lazy import bs4 lazy from bs4 import BeautifulSoup +lazy from pydantic import SecretStr from config import settings lazy from exceptions import MSLMembershipError @@ -28,36 +31,104 @@ {"Cache-Control": "no-cache", "Pragma": "no-cache", "Expires": "0"} ) -BASE_SU_PLATFORM_WEB_COOKIES: Mapping[str, str] = frozendict( - {".AspNet.SharedCookie": settings["SU_PLATFORM_ACCESS_COOKIE"]} -) +AUTH_COOKIE_NAME: Final[str] = ".AspNet.SharedCookie" -MEMBERS_LIST_URL: Final[str] = ( - f"https://guildofstudents.com/organisation/memberlist/{settings['ORGANISATION_ID']}/?sort=groups" +MEMBERS_LIST_URL_TEMPLATE: Final[str] = ( + "https://guildofstudents.com/organisation/memberlist/{organisation_id}/?sort=groups" ) +# NOTE: The cookie the SU platform handed back when it last refreshed the session, paired +# with the configured cookie it was derived from. Holding both means that a cookie set by +# `/config set` replaces this one, rather than being masked by it indefinitely. +_refreshed_auth_cookie: tuple[str, str] | None = None + _membership_list_cache: set[int] = set() +# NOTE: The organisation ID that the cached members-list was fetched for. The organisation +# ID can be changed by `/config set` without a restart, & a members-list fetched for one +# organisation must never be used to accept members of another. +_membership_list_cache_organisation_id: str | None = None + + +def msl_auth_cookie_is_set() -> bool: + """Whether the cookie that authenticates TeX-Bot to the SU platform is set.""" + return settings.community_group.msl.auth_cookie is not None + + +def msl_is_configured() -> bool: + """Whether both of the settings required to reach your group's MSL website are set.""" + return ( + settings.community_group.msl.organisation_id is not None and msl_auth_cookie_is_set() + ) + + +def _configured_auth_cookie() -> str: + """ + Return the MSL authentication cookie held within the configuration. + + Read upon every request, rather than held as a constant, so that a cookie replaced + by `/config set` (the expired-cookie case this setting exists for) takes effect + without TeX-Bot needing to be restarted. + """ + AUTH_COOKIE: Final[SecretStr | None] = settings.community_group.msl.auth_cookie + + if AUTH_COOKIE is None: + NO_AUTH_COOKIE_MESSAGE: Final[str] = ( + "No 'community-group:msl:auth-cookie' was set, " + "so your group's MSL website cannot be accessed." + ) + raise MSLMembershipError(message=NO_AUTH_COOKIE_MESSAGE) + + return AUTH_COOKIE.get_secret_value() + + +def _su_platform_web_cookies() -> Mapping[str, str]: + """Return the cookies that authenticate TeX-Bot to your group's MSL website.""" + CONFIGURED_AUTH_COOKIE: Final[str] = _configured_auth_cookie() + + if _refreshed_auth_cookie is not None and _refreshed_auth_cookie[0] == ( + CONFIGURED_AUTH_COOKIE + ): + return {AUTH_COOKIE_NAME: _refreshed_auth_cookie[1]} + + return {AUTH_COOKIE_NAME: CONFIGURED_AUTH_COOKIE} + + +def _members_list_url() -> str: + """Return the URL of your community group's members-list.""" + ORGANISATION_ID: Final[str | None] = settings.community_group.msl.organisation_id + + if ORGANISATION_ID is None: + NO_ORGANISATION_ID_MESSAGE: Final[str] = ( + "No 'community-group:msl:organisation-id' was set, " + "so your group's members-list cannot be located." + ) + raise MSLMembershipError(message=NO_ORGANISATION_ID_MESSAGE) + + return MEMBERS_LIST_URL_TEMPLATE.format(organisation_id=ORGANISATION_ID) + async def fetch_url_content_with_session(url: str) -> str: """Fetch the HTTP content at the given URL, using a shared aiohttp session.""" - global BASE_SU_PLATFORM_WEB_COOKIES # noqa: PLW0603 + global _refreshed_auth_cookie # noqa: PLW0603 + + SU_PLATFORM_WEB_COOKIES: Final[Mapping[str, str]] = _su_platform_web_cookies() + async with ( aiohttp.ClientSession( - headers=BASE_SU_PLATFORM_WEB_HEADERS, cookies=BASE_SU_PLATFORM_WEB_COOKIES + headers=BASE_SU_PLATFORM_WEB_HEADERS, cookies=SU_PLATFORM_WEB_COOKIES ) as http_session, http_session.get(url=url, ssl=GLOBAL_SSL_CONTEXT) as http_response, ): - returned_asp_cookie: Morsel[str] | None = http_response.cookies.get( - ".AspNet.SharedCookie" - ) + returned_asp_cookie: Morsel[str] | None = http_response.cookies.get(AUTH_COOKIE_NAME) if returned_asp_cookie is not None and ( - returned_asp_cookie.value != BASE_SU_PLATFORM_WEB_COOKIES[".AspNet.SharedCookie"] + returned_asp_cookie.value != SU_PLATFORM_WEB_COOKIES[AUTH_COOKIE_NAME] ): logger.info("SU platform access cookie was updated by the server; updating local.") - BASE_SU_PLATFORM_WEB_COOKIES = { - ".AspNet.SharedCookie": returned_asp_cookie.value, - } + _refreshed_auth_cookie = ( + _configured_auth_cookie(), + returned_asp_cookie.value, + ) return await http_response.text() @@ -67,8 +138,13 @@ async def fetch_community_group_members_list() -> set[int]: Returns a set of IDs. """ + global _membership_list_cache_organisation_id # noqa: PLW0603 + + ORGANISATION_ID: Final[str | None] = settings.community_group.msl.organisation_id + parsed_html: BeautifulSoup = BeautifulSoup( - markup=await fetch_url_content_with_session(MEMBERS_LIST_URL), features="html.parser" + markup=await fetch_url_content_with_session(_members_list_url()), + features="html.parser", ) member_ids: set[int] = set() @@ -114,12 +190,16 @@ async def fetch_community_group_members_list() -> set[int]: _membership_list_cache.clear() _membership_list_cache.update(member_ids) + _membership_list_cache_organisation_id = ORGANISATION_ID return _membership_list_cache async def is_id_a_community_group_member(member_id: int) -> bool: """Check whether the given ID is a member of your community group.""" + if _membership_list_cache_organisation_id != settings.community_group.msl.organisation_id: + _membership_list_cache.clear() + if member_id in _membership_list_cache: return True diff --git a/utils/tex_bot.py b/utils/tex_bot.py index 58327c153..a4bbb6fbf 100644 --- a/utils/tex_bot.py +++ b/utils/tex_bot.py @@ -86,11 +86,10 @@ def main_guild(self) -> discord.Guild: Raises `GuildDoesNotExist` if the given ID does not link to a valid Discord guild. """ MAIN_GUILD_EXISTS: Final[bool] = bool( - self._main_guild - and self._check_guild_accessible(settings["_DISCORD_MAIN_GUILD_ID"]) + self._main_guild and self._check_guild_accessible(settings.discord.main_guild_id) ) if not MAIN_GUILD_EXISTS: - raise GuildDoesNotExistError(guild_id=settings["_DISCORD_MAIN_GUILD_ID"]) + raise GuildDoesNotExistError(guild_id=settings.discord.main_guild_id) return self._main_guild # type: ignore[return-value] @@ -283,10 +282,11 @@ def group_full_name(self) -> str: This is substituted into many error/welcome messages sent into your Discord guild, by TeX-Bot. - The group-full-name is either retrieved from the provided environment variable - or automatically identified from the name of your group's Discord guild. + The group-full-name is either retrieved from the `community-group:full-name` + configuration setting, or automatically identified from the name of your group's + Discord guild. """ - return settings["_GROUP_FULL_NAME"] or ( + return settings.community_group.full_name or ( "The Computer Science Society" if ( "computer science society" in self.main_guild.name.lower() @@ -305,7 +305,7 @@ def group_short_name(self) -> str: """ return ( ( - settings["_GROUP_SHORT_NAME"] + settings.community_group.short_name or ( "CSS" if ( @@ -492,20 +492,20 @@ async def fetch_log_channel(self) -> discord.TextChannel: """ Retrieve the Discord log channel. - If no DISCORD_LOG_CHANNEL_WEBHOOK_URL is specified, + If no `logging:discord-channel:webhook-url` is specified, a ValueError exception will be raised. """ - if not settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"]: + if settings.logging.discord_channel is None: NO_LOG_CHANNEL_MESSAGE: Final[str] = ( "Cannot fetch log channel, " - "when no DISCORD_LOG_CHANNEL_WEBHOOK_URL has been set." + "when no logging:discord-channel:webhook-url has been set." ) raise ValueError(NO_LOG_CHANNEL_MESSAGE) session: aiohttp.ClientSession async with aiohttp.ClientSession() as session: partial_webhook: Webhook = Webhook.from_url( - settings["DISCORD_LOG_CHANNEL_WEBHOOK_URL"], session=session + str(settings.logging.discord_channel.webhook_url), session=session ) full_webhook: Webhook = await partial_webhook.fetch() diff --git a/uv.lock b/uv.lock index 290a589b3..f09c26f8d 100644 --- a/uv.lock +++ b/uv.lock @@ -82,6 +82,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, ] +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + [[package]] name = "application-properties" version = "0.8.3" @@ -944,6 +953,62 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/e2/480bcdb153feecde4d736b18c908c7eee4846f11d7547d2e0c71499af630/pycodestyle-2.15.0-py2.py3-none-any.whl", hash = "sha256:12fd2f73c7b8ee8845a0431111df8faf4c1a07d6e64e2ee7f0c74014dab14181", size = 31583, upload-time = "2026-09-22T22:15:34.007Z" }, ] +[[package]] +name = "pydantic" +version = "2.14.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/25/3ec212432a6031b65f043eaca9c820ddf87c0d0aa330023e64f79fcb5db6/pydantic-2.14.4.tar.gz", hash = "sha256:7c19f1d46f8accf55a4617a6116e1ade64840870f397b846a2c53fb9019414ba", size = 927354, upload-time = "2026-11-19T12:57:39.767Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/8c/824a686c4ba815ddb0722f9e66272088bccd4e1ae1d2f7015375e4a4fc7f/pydantic-2.14.4-py3-none-any.whl", hash = "sha256:653a2ad9f6d8858529c77c72717d0ea991d6c6837fe683246b2f4b2bbfc3fadc", size = 494865, upload-time = "2026-11-19T12:57:37.688Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fb/63/0ceb815a7762576027ce388544c573d440574f95afb1302a2496b96db548/pydantic_core-2.50.5.tar.gz", hash = "sha256:1e740886083ff95530d694e6a3f09ed914bcf92a496d16acd307c6c3484fc36d", size = 523285, upload-time = "2026-11-19T12:56:38.067Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/34/7c/7ab4dd1eaad75d20c596a4b2a36961a98f344aa0bad2938edbe644214baa/pydantic_core-2.50.5-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:c4c4313dc66f45822b3d7f39aa74e59e7987cf7572b3309005b26d956a0098a9", size = 2245524, upload-time = "2026-11-19T12:55:31.444Z" }, + { url = "https://files.pythonhosted.org/packages/ac/29/2cc2423f489d4526825d2371d047de505760260462eb72d838fc5e934aca/pydantic_core-2.50.5-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:e93587aaa5660536b9188686e8fe0544b577ec57d896d424b5b2118b151a6845", size = 2116389, upload-time = "2026-11-19T12:55:32.66Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f7/f7fdfbb6ccacf4ef3a4757eab9ecb9d5809b2568bf38e8f41b1872524f23/pydantic_core-2.50.5-cp315-cp315-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:0a7d599d0c5afbab98c0e4441f5b76163c6fcfd2ecf73dd6418e468a7ac452b8", size = 2266368, upload-time = "2026-11-19T12:55:34.366Z" }, + { url = "https://files.pythonhosted.org/packages/91/3f/8d12c17b4a55097c164759b38136bbd2abe3f2668f0d908fd3d0d4a7e0fd/pydantic_core-2.50.5-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:568e928322f0b6b94671fc1a4dbc867627af74695b0c060ac6d4f25b6a7425d8", size = 2138673, upload-time = "2026-11-19T12:55:35.629Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c0/54c3746f13409b9674f812cd37c98da25df970d030d9260e9e904205893c/pydantic_core-2.50.5-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:bdafd6b05bf012772b7d7325a98d26f19b7918e21dabdd5970c885262245aae3", size = 2203145, upload-time = "2026-11-19T12:55:37.366Z" }, + { url = "https://files.pythonhosted.org/packages/79/3a/91f0e7ffc5626a673804fdd33a007186c06352020199653e3df4b5a43ad5/pydantic_core-2.50.5-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:008de9d97f2b0c8e596fb5d93d49b63be158e8be5ac35856903b338cbcfd21f3", size = 2397558, upload-time = "2026-11-19T12:55:38.615Z" }, + { url = "https://files.pythonhosted.org/packages/a6/51/bc916df37f46f77d5159e4a438033702bdbde47814dd407e97fb1aef6fb1/pydantic_core-2.50.5-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:f8fd7e9c44bb4c9214d41c3bef79cba5a513b29c3bcbfdaaf0440ca6f5fb65ea", size = 2478927, upload-time = "2026-11-19T12:55:39.847Z" }, + { url = "https://files.pythonhosted.org/packages/e9/8f/a8f56878763b6fdeca69b73d9b4c44aa4526bfa6a386da21792ed0b766ce/pydantic_core-2.50.5-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0d6e614776c8c99495dcfc6ce8f826277fb4388a5e5cbee23c199cbe39e6dcb3", size = 2276148, upload-time = "2026-11-19T12:55:41.379Z" }, + { url = "https://files.pythonhosted.org/packages/a5/bf/2c28071bb81fe07595ca8d08011ea1005bae92d2b0cb43ce768a135105e0/pydantic_core-2.50.5-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:bcd9d9b38e61dfd43e00f621ce00da2ffed35047fad532c4afcadf4f9ca0d672", size = 2279590, upload-time = "2026-11-19T12:55:42.856Z" }, + { url = "https://files.pythonhosted.org/packages/62/d9/905d95bdb65ce24ca27149796fba3869db2bed08e0688c8dbe863d916b56/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:4888829471cd8d85c096ef0e1f41a066c7d76e88309a4fbff4069f70d07673be", size = 2310233, upload-time = "2026-11-19T12:55:44.114Z" }, + { url = "https://files.pythonhosted.org/packages/08/d0/6d63888afef31cda359ba122d768ae83c59213afc3cde4a528a67f4e7d80/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:ad0e0221deec2a2385300d76b9259da7036c0ed784502c154ae237dafd67605f", size = 2478319, upload-time = "2026-11-19T12:55:45.299Z" }, + { url = "https://files.pythonhosted.org/packages/33/f6/de8de17435f95dd8ad0db86d74beea9195cfbfce5434946a0bb53e025be5/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:20337f547d79911457cd4739bb6699213a53089f946af87633a48fad3f74f5e1", size = 2508289, upload-time = "2026-11-19T12:55:46.634Z" }, + { url = "https://files.pythonhosted.org/packages/f4/39/aae7e3187162752675094b970cb6294bf10ba091f33eebc35376d1b3f0aa/pydantic_core-2.50.5-cp315-cp315-win32.whl", hash = "sha256:09c732c097816c89d46ddb70f89d72e853e3a1bbac6475961c60a88aad9fe612", size = 2131982, upload-time = "2026-11-19T12:55:47.819Z" }, + { url = "https://files.pythonhosted.org/packages/c6/81/abd633f5fafcb06991a311293b37783ea3ea0b23c11845282bf24d7ddab8/pydantic_core-2.50.5-cp315-cp315-win_amd64.whl", hash = "sha256:0d4edc3350e21e0ef773ef9395227ca072832f05e484cadcf4d8663b63a231c0", size = 2285739, upload-time = "2026-11-19T12:55:49.198Z" }, + { url = "https://files.pythonhosted.org/packages/69/6c/0b678e369c45edf0e47b4ceefcb9ac86cf81d7440ad780c384dfeddf7eff/pydantic_core-2.50.5-cp315-cp315-win_arm64.whl", hash = "sha256:af453c0c20372ca8acf3c46de2a89b242491853dc61d0171ba24608d33310e09", size = 2176798, upload-time = "2026-11-19T12:55:50.779Z" }, + { url = "https://files.pythonhosted.org/packages/4e/f2/9907ab2bb673ae2f4ccb6b026e201a5d38cbf9a4f109050b681b8aebf7e9/pydantic_core-2.50.5-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:9e255e7c32d9c2f396d3daa833e7d8d701eec7bf8e13ca092b4b83ce7d9487fd", size = 2235810, upload-time = "2026-11-19T12:55:52.04Z" }, + { url = "https://files.pythonhosted.org/packages/65/c4/caa101ff8599aedb41816c987f44bd7c9d8d5ae42740589da1cf60ce4545/pydantic_core-2.50.5-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c334b8759496f9e597b68e1309b2fb3d824fd24a29e562afa86b61005eb9d54d", size = 2094628, upload-time = "2026-11-19T12:55:53.353Z" }, + { url = "https://files.pythonhosted.org/packages/91/34/253060ed9f5df44edc3632261b0a457407935b3454dfd40230f5a60f6503/pydantic_core-2.50.5-cp315-cp315t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:90dabbf4f38f37de1663ce932d37c6f694a005f6470ae2f0d97755d9e3f90ffd", size = 2275436, upload-time = "2026-11-19T12:55:55.061Z" }, + { url = "https://files.pythonhosted.org/packages/9f/bb/2c0b69f1959370f21abb84751c1ef42d73edad84ee6ed67975e6ca6aa194/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5ec2e8caf5eadea7be683fc7025d60563e920f1f52fe18ae46c49558e67b8cd0", size = 2118960, upload-time = "2026-11-19T12:55:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/3f/74/f6c32d48da403d63fd8860af73c2edf7f0b05346078fa7d3fa7b9af59492/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:44e6c35bf3a9b6785db0c083df8a6929343f9c8fc27186991d21653242c77c19", size = 2204816, upload-time = "2026-11-19T12:55:57.807Z" }, + { url = "https://files.pythonhosted.org/packages/fb/10/a2cb0da341bd09c2d102d50f126827fe79d78611526f8d26c55e1d9e13a5/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f33be114a0ee27870cffd31057ed60bf5a0cd522dcbdc1dda0bdad70f8302cb0", size = 2420693, upload-time = "2026-11-19T12:55:59.129Z" }, + { url = "https://files.pythonhosted.org/packages/40/31/f8c0ab3f77fb4e348ff818f49f272d2f833aadd3478de4919ccfce10736e/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:12178e58af383bd4c32b2fe141188bc7e540c5eb33ad550856fa5863b4c31bd5", size = 2482316, upload-time = "2026-11-19T12:56:00.438Z" }, + { url = "https://files.pythonhosted.org/packages/82/fc/134b0a1a06971c84f2a3bc6e1123cac9c3d58e8a67b6ef951a0b97f160d1/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:679f15dd3bd2a82bde350ec8c94c0f8f05f05dba39fb3464cd4136a724da9844", size = 2268676, upload-time = "2026-11-19T12:56:01.985Z" }, + { url = "https://files.pythonhosted.org/packages/7b/c0/b5f34860606866a918cd934172b24fd6069ffbac13179635f65ca3516aea/pydantic_core-2.50.5-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:11806d9b4888f1645d74fc24237f21dad559b42fb8930481b3df414997be6ee5", size = 2276349, upload-time = "2026-11-19T12:56:03.265Z" }, + { url = "https://files.pythonhosted.org/packages/7a/6c/728833b2c94a446f0bfcb5fc82e039aa6da648fdcd925aa8b612e66e142c/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:b43115385de7db83bd2fe7a08dea8580bce3acc3f54200c4f4fe32a4a49688d4", size = 2320015, upload-time = "2026-11-19T12:56:04.519Z" }, + { url = "https://files.pythonhosted.org/packages/4b/c6/c9a9c08eb46517a2028d40cf6cd58674c82ba0912e172ed7a37362e1219c/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:86bd5aad5ccbaced98139d08b4314f253c086897830f4bcf9c1d1f02f740683d", size = 2480855, upload-time = "2026-11-19T12:56:05.809Z" }, + { url = "https://files.pythonhosted.org/packages/4b/e4/7cdac28f4e0b587d66ef34ec5a0e3114ed8a383db958122495d85c03377a/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:90ff55049623eccbfa997332e2b91358dc2c4c30ca6e664b45438723cbe181df", size = 2525363, upload-time = "2026-11-19T12:56:07.301Z" }, + { url = "https://files.pythonhosted.org/packages/82/99/70305ab96334631da7cf3b20de4ea433589a5a022b28b9a3a0cc1c08b435/pydantic_core-2.50.5-cp315-cp315t-win32.whl", hash = "sha256:7c3faea08d44b4a7b57b30f1113e6404e6aa62a4f3489a22359fb27d6003d8b1", size = 2114429, upload-time = "2026-11-19T12:56:08.521Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f2/98c0c74b43877bad2aa16332498626b375ff63d4e5f85c4d09b08d14f861/pydantic_core-2.50.5-cp315-cp315t-win_amd64.whl", hash = "sha256:b2b64d3204f9c33f03ed3111eb754902ea76ca5aa61ab4b2bdf9f767a4a1f279", size = 2251995, upload-time = "2026-11-19T12:56:09.711Z" }, + { url = "https://files.pythonhosted.org/packages/70/17/8ead84e326315b8c99165f3388ccc2b2355a4a2c8bdcba4b9241823dc064/pydantic_core-2.50.5-cp315-cp315t-win_arm64.whl", hash = "sha256:8ba2dcbeea0ab8836e804c54e905075125c702cf78e592d998eecf2764b64144", size = 2185080, upload-time = "2026-11-19T12:56:10.948Z" }, +] + [[package]] name = "pyflakes" version = "4.1.0" @@ -1089,6 +1154,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "ruamel-yaml" +version = "0.19.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/3b/ebda527b56beb90cb7652cb1c7e4f91f48649fbcd8d2eb2fb6e77cd3329b/ruamel_yaml-0.19.1.tar.gz", hash = "sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993", size = 142709, upload-time = "2026-01-02T16:50:31.84Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/0c/51f6841f1d84f404f92463fc2b1ba0da357ca1e3db6b7fbda26956c3b82a/ruamel_yaml-0.19.1-py3-none-any.whl", hash = "sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93", size = 118102, upload-time = "2026-01-02T16:50:29.201Z" }, +] + [[package]] name = "ruff" version = "0.17.6" @@ -1168,10 +1242,11 @@ main = [ { name = "mplcyberpunk" }, { name = "parsedatetime" }, { name = "py-cord" }, + { name = "pydantic" }, { name = "python-dotenv" }, { name = "python-logging-discord-handler" }, + { name = "ruamel-yaml" }, { name = "typed-classproperties" }, - { name = "validators" }, ] pre-commit = [ { name = "prek" }, @@ -1218,10 +1293,11 @@ main = [ { name = "mplcyberpunk", specifier = ">=0.7" }, { name = "parsedatetime", specifier = ">=2.6" }, { name = "py-cord", specifier = ">=2.8" }, + { name = "pydantic", specifier = ">=2.13" }, { name = "python-dotenv", specifier = ">=1.0" }, { name = "python-logging-discord-handler", specifier = ">=0.1" }, + { name = "ruamel-yaml", specifier = ">=0.19" }, { name = "typed-classproperties", specifier = ">=1.2" }, - { name = "validators", specifier = ">=0.34" }, ] pre-commit = [{ name = "prek", specifier = ">=0.5.3" }] test = [ @@ -1330,6 +1406,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + [[package]] name = "tzdata" version = "2026.6" @@ -1348,15 +1436,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] -[[package]] -name = "validators" -version = "0.36.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7b/3f/4fe7905f73ba0e768baa102a09ba9458f2f0bb4a676102e1fd7a3cb55c2b/validators-0.36.0.tar.gz", hash = "sha256:92ad9ed00bbed320b784cec0ea90b213cf08904cf605b3d0852cfa4108e32a2c", size = 79234, upload-time = "2026-10-11T11:01:31.682Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d5/ce/fc5090ea3789bdfd22e90f2515b237194c5dacfc8f26d2082a0b50b2ca86/validators-0.36.0-py3-none-any.whl", hash = "sha256:c52ad00435e385b95fa4d6dd3081cb20c0660e7fd07b214523c8584dd2edba34", size = 46040, upload-time = "2026-10-11T11:01:30.269Z" }, -] - [[package]] name = "wcwidth" version = "0.9.5"