diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..04e2478b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,36 @@ +# Exclude env files at any depth (**/*.env) — Docker patterns without '/' are +# root-anchored (unlike gitignore) and miss subdirectories. +# config_sample.env is re-included below; order matters, last match wins. +# Without this file, COPY . . bakes env files and virtualenvs into the image. +.git +.gitattributes +**/*.env +!config_sample.env +**/*.session +**/*.session-journal +**/*.session-shm +**/*.session-wal +Thunder/logs +.venv +venv +__pycache__ +**/__pycache__ +**/*.pyc +.pytest_cache +.ruff_cache +.coverage +.coverage.* +.coverage.json +tests +requirements-dev.txt +pyproject.toml +.github +.gitignore +.python-version +Dockerfile +.dockerignore +README.md +AGENTS.md +VPS.md +PLAN.md + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..543655fe --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + # Actions are pinned to commit SHAs, so they need updates to move. + # Application dependencies are deliberately left floating. + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/dockerize.yml b/.github/workflows/dockerize.yml deleted file mode 100644 index a810be6b..00000000 --- a/.github/workflows/dockerize.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Docker Build & Push - -on: - push: - branches: [main] - workflow_dispatch: - -jobs: - build: - if: github.repository == 'fyaz05/FileToLink' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - - name: Login to Docker Hub - uses: docker/login-action@v3 - with: - username: fyaz05 - password: ${{ secrets.DOCKER_TOKEN }} - - - name: Build and Push - uses: docker/build-push-action@v6 - with: - context: . - push: true - tags: fyaz05/thunder:latest diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f59f9e39..34b82412 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,26 +1,119 @@ -name: Tests +name: CI on: push: branches: [main] pull_request: workflow_dispatch: + schedule: + # Dependencies float on purpose, so a weekly run is the only thing that + # notices a bad upstream release before a user does. + - cron: "30 4 * * 1" + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # Only PR runs race. Cancelling a publish to Docker Hub midway is worse than + # letting it finish. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - pytest: + test: + # Runs on the upstream repository, not in every fork. if: github.repository == 'fyaz05/FileToLink' - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Windows earns its place: the uvloop marker and update.py's chmod + # fallback never execute on Linux. + os: [ubuntu-latest, windows-latest] + python-version: ["3.13"] + include: + # The image pins 3.13, but the project documents 3.13+ support and the + # dependencies float, so this is what proves the promise still holds. + - os: ubuntu-latest + python-version: "3.14" + runs-on: ${{ matrix.os }} + timeout-minutes: 20 steps: - - uses: actions/checkout@v5 - - - uses: actions/setup-python@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: - python-version: "3.13" - + python-version: ${{ matrix.python-version }} - name: Install run: | python -m pip install --upgrade pip pip install -r requirements-dev.txt - + pip check - name: Test run: python -m pytest -q + - name: Lint + run: python -m ruff check . + + build: + # Waiting for the tests is what stops a red main from publishing. + needs: [test] + if: github.repository == 'fyaz05/FileToLink' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Set up Buildx + # The default docker driver writes to the daemon's image store, and the + # classic store cannot hold an image index, so an explicit provenance + # attestation fails there. A container-driver builder supports them + # regardless, and also keeps the result addressable for the smoke test. + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - name: Log in to Docker Hub + # Fork pull requests never receive secrets, so logging in there would + # only fail. The image still builds without credentials. + if: github.event_name == 'push' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + username: fyaz05 + password: ${{ secrets.DOCKER_TOKEN }} + - name: Build and push + id: build + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + # Loaded, not pushed, and without attestations: this build exists to be + # tested, and the publish step below rebuilds from the same cache. An + # attestation cannot be loaded into the daemon's image store, so asking + # for one here would fail before the test ever ran. Passing no tag keeps + # this image out of the registry entirely. + load: true + tags: fyaz05/thunder:test + - name: Smoke test the built image + # Building is not the same as working: a missing dependency or a broken + # import still produces a valid image that fails the moment it starts. + # This runs BEFORE anything is published, so a broken image is never the + # one tagged latest. Importing the entry point is the strongest check that + # needs no real credentials -- Thunder.vars validates its configuration at + # import, so placeholders stand in for a deployment's own values. That + # also means this proves the dependencies and the code, not the config. + run: | + docker run --rm \ + -e API_ID=123456 \ + -e API_HASH=00000000000000000000000000000000 \ + -e BOT_TOKEN=123456:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \ + -e BIN_CHANNEL=-1001234567890 \ + -e OWNER_ID=1 \ + -e DATABASE_URL=mongodb://localhost:27017/smoke \ + fyaz05/thunder:test python -c \ + "import Thunder, Thunder.__main__, uvloop, tgcrypto, aiohttp; print('ok', Thunder.__version__)" + - name: Publish + # Only reached once the smoke test passed, and only for a push event: a + # pull request never receives secrets. Rebuilds from the cache the tested + # build populated, so this is the same image, now with attestations. + if: github.event_name == 'push' + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + # Public and private repositories default differently, so it is set + # explicitly. + provenance: mode=max + push: true + tags: fyaz05/thunder:latest diff --git a/.gitignore b/.gitignore index a9dc32e4..eee0f579 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,14 @@ *$py.class *.so .venv/ +venv/ .Python -config.env +# Exclude env files (a stray `git add -A` must not pick them up); track only the template. +*.env +!config_sample.env +# Local operational files containing credentials or scratch notes. +VPS.md +PLAN.md log.text .vscode/ **/__pycache__/ @@ -28,5 +34,9 @@ wheels/ .installed.cfg *.egg .pytest_cache/ +.ruff_cache/ +.coverage +.coverage.* +.coverage.json __pycache__/ *.pyc diff --git a/AGENTS.md b/AGENTS.md index 57b94d21..f4d0fd3f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,14 +8,15 @@ Python 3.13+ Telegram bot converting files to direct HTTP links. Uses Pyrofork, python -m Thunder # Primary entry point bash thunder.sh # Updates from UPSTREAM_REPO, then runs the bot python3 update.py # Update only (rolls back if the new tree is unusable) +# update.py exits 0 when it cannot apply: no UPSTREAM_REPO, or no git/.git in a container ``` ## Dependencies ```bash pip install -r requirements.txt -# aiohttp, cloudscraper, Jinja2, pyrofork, pymongo, psutil, python-dotenv, speedtest-cli, tgcrypto -# uvloop==0.21.0 only on non-Windows/Cygwin (requirements.txt marker); asyncio loop elsewhere +# aiohttp, cloudscraper, Jinja2, pyrofork, pymongo, psutil, python-dotenv, speedtest-cli, tgcrypto-pyrofork +# uvloop (non-Windows/Cygwin only, requirements.txt marker); asyncio loop elsewhere ``` ## Project Structure @@ -29,7 +30,7 @@ Thunder/ │ ├── __init__.py # StreamBot client, multi_clients, work_loads │ ├── clients.py # Multi-client management │ └── plugins/ -│ ├── admin.py # Owner commands: /users /broadcast /status /stats /restart /log /authorize /deauthorize /ban /unban /shell /speedtest +│ ├── admin.py # Owner commands: /users /broadcast /status /stats /restart /log /authorize /deauthorize /listauth /ban /unban /shell /speedtest │ ├── callbacks.py # Inline keyboard handlers │ ├── common.py # User commands: /start /help /about /dc /ping │ └── stream.py # /link (groups), private/channel media handlers @@ -38,9 +39,26 @@ Thunder/ │ ├── stream_routes.py # HTTP streaming endpoints │ └── exceptions.py # Custom HTTP exceptions ├── utils/ # 20 modules — see imports below -└── template/ # dl.html, req.html (Jinja2) +└── template/ # req.html (Jinja2) ``` +## Docker + +The image runs as unprivileged user `10001` and installs no build toolchain (all +dependencies provide wheels). `.dockerignore` excludes env files, session files, +virtualenvs, dev tools, and tests; supply `config.env` at runtime. + +Two gotchas: +- A mounted `config.env` must be readable by uid `10001` (`chmod 644`; a + root-only `600` fails). Do not `chown` it — that hands the file to a host-unknown + uid you can no longer edit. +- Docker's `--env-file` passes values verbatim, so inline comments and quotes in + `config_sample.env` corrupt variables (`PORT` becomes `8080 # Web server port`). + Generate the file with `python-dotenv` outside the repo (see README), or mount `config.env`. + +Self-update is skipped inside the image: there is no `git` and no `.git`, so +`UPSTREAM_REPO` has no effect there. Update a container by building a new image. + ## Key Imports ```python @@ -77,16 +95,46 @@ Copy `config_sample.env` → `config.env`. Required vars: `API_ID`, `API_HASH`, ## Testing ```bash -pip install pytest pytest-asyncio -python -m pytest -q # ~60s; no network or Telegram credentials needed +pip install -r requirements-dev.txt +python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials needed +python -m ruff check . # config lives in pyproject.toml ``` Covers request parsing, slot conservation and truncation on the streaming -routes, the import cycle, database naming, /status before startup, and -update.py preconditions and rollback. +routes, the import cycle, database naming, /status before startup, +update.py preconditions and rollback, plugin handler registration, the CI +workflow's invariants, and .gitignore hygiene. + +`pytest` and `ruff` both read `pyproject.toml`; there is no `pytest.ini`. + +### With uv + +`uv` is faster than pip for creating environments and installing, and it is used +only as a tool — there is deliberately **no `uv.lock`**: pinning every package is +the opposite of what this project wants, because `requirements.txt` floats so that +CI notices a bad upstream release. Every command below was run to confirm it works +and leaves no lock file: + +```bash +uv venv .venv --python 3.13 # ~0.15s +uv pip install --python .venv/bin/python -r requirements-dev.txt # ~3s first time +uvx ruff check . # ~0.1s, no install needed +``` + +On Windows the interpreter is `.venv\Scripts\python.exe`. `uv pip install` runs in +well under a second once anything is installed; the first install after creating +the environment takes a few seconds. Re-running it is safe. + +One caveat if you deploy from this checkout: `uv venv` creates an environment +**without pip**, and `update.py` installs dependencies on a self-update with +`python -m pip`. It falls back to `uv pip` and warns if neither works, but the +cleanest result comes from seeding pip in the first place: + +```bash +uv venv --seed .venv --python 3.13 # includes pip +``` ## Debugging - Logs: Thunder/logs/bot.txt -- Health check: admin /status command, or GET /status on the web port -- No linting/formatting tools configured - follow conventions manually \ No newline at end of file +- Health check: admin /status command, or GET /status on the web port \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 63d8ea78..102291b2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,21 +5,18 @@ ENV PYTHONUNBUFFERED=1 \ WORKDIR /app -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - git \ - build-essential \ - libssl-dev \ - && apt-get clean && \ - rm -rf /var/lib/apt/lists/* - +# No build toolchain needed: dependencies provide prebuilt wheels (see requirements.txt). COPY requirements.txt . -RUN pip install --upgrade pip && \ - pip install --no-cache-dir -r requirements.txt +RUN pip install --no-cache-dir -r requirements.txt + +# Owned by unprivileged user so Thunder/logs and session file can be written at runtime. +COPY --chown=10001:10001 . . + +USER 10001:10001 -COPY . . +EXPOSE 8080 -# Update from UPSTREAM_REPO when it is configured, then start. A failed or -# skipped update never blocks startup. +# Start. thunder.sh tries update.py first; with no git or .git in the image that +# is reported as not applicable and the bot starts on the code baked in here. CMD ["bash", "thunder.sh"] diff --git a/README.md b/README.md index a609787d..b3814715 100644 --- a/README.md +++ b/README.md @@ -307,13 +307,52 @@ cd FileToLink cp config_sample.env config.env nano config.env # Edit your settings -# 3. Build and run +# 3. Build and run (the config is mounted — it is not baked into the image) docker build -t thunder . -docker run -d --name thunder -p 8080:8080 thunder -# Optional: --stop-timeout 30 lets the server's 25s shutdown drain finish (docker stop defaults to 10s) -docker run -d --stop-timeout 30 --name thunder -p 8080:8080 thunder +docker run -d --name thunder -p 8080:8080 \ + -v "$PWD/config.env:/app/config.env:ro" thunder ``` +(PowerShell: `-v "${PWD}\config.env:/app/config.env:ro"`.) + +The container runs as uid `10001`, which is not you, so `config.env` must be +readable by others. A file created with a normal umask (`cp` gives `644`) already +is; if yours is `600`, widen it without changing ownership: + +```bash +chmod 644 config.env +``` + +`--stop-timeout 30` is optional — it lets the server's 25s shutdown drain +finish, since `docker stop` defaults to 10s: + +```bash +docker run -d --stop-timeout 30 --name thunder -p 8080:8080 \ + -v "$PWD/config.env:/app/config.env:ro" thunder +``` + +The image runs as unprivileged user `10001` without a build toolchain. Env files are +excluded from the build context (`.dockerignore`), so `config.env` is not baked in and +must be supplied at runtime. + +
+Alternative: pass configuration as environment variables + +Docker's `--env-file` passes values verbatim, so inline comments and quotes in +`config_sample.env` (`HAS_SSL="True" # ...`) corrupt variables. Generate a clean file +using `python-dotenv`: + +```bash +python3 -c "from dotenv import dotenv_values as d; [print(f'{k}={v}') for k, v in d('config.env').items()]" > /tmp/thunder-docker.env +docker run -d --name thunder -p 8080:8080 --env-file /tmp/thunder-docker.env thunder +``` + +Requires `python-dotenv` locally (`pip install python-dotenv`); mounting `config.env` +avoids this step. Keep the generated file outside the repository so it cannot enter the +build context. + +
+
Manual Installation @@ -388,14 +427,19 @@ After deployment, to add any additional environment variables, use the Koyeb das ```bash heroku ps:scale web=1 ``` -7. Restarts update from `UPSTREAM_REPO` automatically; a failed update rolls back instead of starting a broken tree: +7. Restarts update from `UPSTREAM_REPO` only when the deployment has a git checkout. A Heroku slug is built from a tarball (step 5) and carries no `.git`, so the update is skipped and the dyno starts on the code in the slug. Durable changes need a new slug: ```bash + # Only takes effect on a deployment that has a .git directory (e.g. a VM checkout). heroku config:set UPSTREAM_REPO="https://github.com/fyaz05/FileToLink" UPSTREAM_BRANCH="main" - # The dyno filesystem is ephemeral, so a durable change still needs a new slug (step 5). ``` > **Note:** Heroku provides HTTPS automatically. Set `FQDN` to `your-app-name.herokuapp.com` and `HAS_SSL` to `True`. +> **Note:** `heroku.yml` builds this repo's `Dockerfile`, so the dyno runs as uid `10001` +> and cannot read a root-only `config.env`. Config vars avoid the file entirely, which is +> why this path uses them; the container's own `Thunder/logs` is already writable from the +> image, so no `chmod` step is needed here. + > **Note:** See the [Configuration](#configuration) section for required environment variables. ## Reverse Proxy Setup @@ -559,9 +603,18 @@ Contributions are welcome! Please follow these steps: 1. Fork the repository. 2. Create a new feature branch (`git checkout -b feature/amazing-feature`). -3. Commit your changes (`git commit -m 'Add some amazing feature'`). -4. Push to the branch (`git push origin feature/amazing-feature`). -5. Open a Pull Request. +3. Make your change and run the suite and linter: + ```bash + pip install -r requirements-dev.txt + python -m pytest -q + python -m ruff check . + ``` +4. Commit your changes (`git commit -m 'Add some amazing feature'`). +5. Push to the branch (`git push origin feature/amazing-feature`). +6. Open a Pull Request. + +CI runs the suite on Linux and Windows, then builds the image only once those +pass. ## License @@ -572,7 +625,7 @@ Licensed under the [Apache License 2.0](LICENSE). See the `LICENSE` file for det - [Pyrofork](https://github.com/Mayuri-Chan/pyrofork) - Telegram MTProto API Framework - [aiohttp](https://github.com/aio-libs/aiohttp) - Asynchronous HTTP Client/Server - [PyMongo](https://github.com/mongodb/mongo-python-driver) - Asynchronous MongoDB Driver -- [TgCrypto](https://github.com/pyrogram/tgcrypto) - High-performance cryptography library +- [TgCrypto](https://github.com/wulan17/tgcrypto-pyrofork) - High-performance cryptography library ## ⚠️ Disclaimer diff --git a/Thunder/__init__.py b/Thunder/__init__.py index 4e32f5df..d9af44e8 100644 --- a/Thunder/__init__.py +++ b/Thunder/__init__.py @@ -1,4 +1,3 @@ -# Thunder/__init__.py import time diff --git a/Thunder/__main__.py b/Thunder/__main__.py index df6786bf..b9e5ecee 100644 --- a/Thunder/__main__.py +++ b/Thunder/__main__.py @@ -1,4 +1,8 @@ -# Thunder/__main__.py +"""Entry point: builds the event loop, then starts clients and the web server. + +The loop is created before the Pyrogram imports on purpose; see the comment +below. Run with ``python -m Thunder``. +""" import asyncio import glob @@ -318,7 +322,7 @@ async def start_services(): try: await db.close() print(" ✓ Database connection closed") - except Exception as e: + except Exception: logger.error("Error during database cleanup", exc_info=True) diff --git a/Thunder/bot/__init__.py b/Thunder/bot/__init__.py index 1e28c42b..33250027 100644 --- a/Thunder/bot/__init__.py +++ b/Thunder/bot/__init__.py @@ -1,4 +1,4 @@ -# Thunder/bot/__init__.py +"""The primary Pyrogram client and the shared workload tables.""" from pyrogram import Client from Thunder.vars import Var diff --git a/Thunder/bot/clients.py b/Thunder/bot/clients.py index f27dfc85..5f690301 100644 --- a/Thunder/bot/clients.py +++ b/Thunder/bot/clients.py @@ -1,4 +1,8 @@ -# Thunder/bot/clients.py +"""Starts the extra bot clients from MULTI_TOKEN* and spreads the load. + +The primary client is created in Thunder.bot; this module adds the rest and +is what the /stats and /status commands report against. +""" import asyncio diff --git a/Thunder/bot/plugins/admin.py b/Thunder/bot/plugins/admin.py index 82d0e729..e5743f9c 100644 --- a/Thunder/bot/plugins/admin.py +++ b/Thunder/bot/plugins/admin.py @@ -1,4 +1,7 @@ -# Thunder/bot/plugins/admin.py +"""Owner commands: users, broadcast, status, stats, restart, logs, shell. + +Every handler here is registered with ``filters.user(Var.OWNER_ID)``. +""" import asyncio import html @@ -178,7 +181,14 @@ async def show_stats(client: Client, message: Message): async def restart_bot(client: Client, message: Message): msg = await reply(message, text=MSG_RESTARTING) await db.add_restart_message(msg.id, message.chat.id) - os.execv("/bin/bash", ["bash", "thunder.sh"]) + + # thunder.sh runs update.py before starting, so prefer it where it can run. + # It is a bash script, so Windows restarts the interpreter directly and skips + # the update step rather than crashing on a path that does not exist. + bash = shutil.which("bash") + if os.name != "nt" and bash: + os.execv(bash, ["bash", "thunder.sh"]) + os.execv(sys.executable, [sys.executable, "-m", "Thunder"]) @StreamBot.on_message(filters.command("log") & owner_filter) diff --git a/Thunder/bot/plugins/callbacks.py b/Thunder/bot/plugins/callbacks.py index ab6d71a1..a53a7232 100644 --- a/Thunder/bot/plugins/callbacks.py +++ b/Thunder/bot/plugins/callbacks.py @@ -1,4 +1,8 @@ -# Thunder/bot/plugins/callbacks.py +"""Inline keyboard handlers: help, about, broadcast cancel and panel close. + +Callback data is the only trusted input here, since the message it arrives on +was sent by the bot. +""" import asyncio diff --git a/Thunder/bot/plugins/common.py b/Thunder/bot/plugins/common.py index a773b522..5bd75830 100644 --- a/Thunder/bot/plugins/common.py +++ b/Thunder/bot/plugins/common.py @@ -1,4 +1,4 @@ -# Thunder/bot/plugins/common.py +"""User commands: /start /help /about /dc /ping.""" import asyncio import time diff --git a/Thunder/bot/plugins/stream.py b/Thunder/bot/plugins/stream.py index 02c3368a..4fcce1e1 100644 --- a/Thunder/bot/plugins/stream.py +++ b/Thunder/bot/plugins/stream.py @@ -1,4 +1,8 @@ -# Thunder/bot/plugins/stream.py +"""Link generation: /link in groups, and media sent to the bot in private. + +Forwards media to the storage channel, records the canonical file entry, and +replies with the direct download and streaming links. +""" import asyncio import secrets diff --git a/Thunder/server/__init__.py b/Thunder/server/__init__.py index 034a61a3..9089d9b2 100644 --- a/Thunder/server/__init__.py +++ b/Thunder/server/__init__.py @@ -1,4 +1,3 @@ -# Thunder/server/__init__.py from aiohttp import web diff --git a/Thunder/server/exceptions.py b/Thunder/server/exceptions.py index b25ef7ec..1994cad7 100644 --- a/Thunder/server/exceptions.py +++ b/Thunder/server/exceptions.py @@ -1,4 +1,3 @@ -# Thunder/server/exceptions.py class InvalidHash(Exception): pass diff --git a/Thunder/server/stream_routes.py b/Thunder/server/stream_routes.py index 9ce7ed9c..1512a1ce 100644 --- a/Thunder/server/stream_routes.py +++ b/Thunder/server/stream_routes.py @@ -1,4 +1,8 @@ -# Thunder/server/stream_routes.py +"""HTTP surface: direct downloads, streaming, and the player page. + +Serves /f// and the short-hash form, honouring Range requests so +large files seek, plus the /watch pages that wrap a file in a player. +""" import re import secrets @@ -318,7 +322,7 @@ async def canonical_media_preview(request: web.Request): file_name = file_record.get("file_name") or f"file_{secure_hash}" src = f"{Var.URL.rstrip('/')}/f/{secure_hash}/{quote_media_name(file_name)}" - rendered_page = await render_media_page(file_name, src, requested_action='stream') + rendered_page = await render_media_page(file_name, src) response = web.Response( text=rendered_page, @@ -347,8 +351,7 @@ async def media_preview(request: web.Request): path = request.match_info["path"] message_id, secure_hash = parse_media_request(path, request.query) - rendered_page = await render_page( - message_id, secure_hash, requested_action='stream') + rendered_page = await render_page(message_id, secure_hash) response = web.Response( text=rendered_page, diff --git a/Thunder/template/dl.html b/Thunder/template/dl.html deleted file mode 100644 index a0e3bb45..00000000 --- a/Thunder/template/dl.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - Downloading: {{ file_name }} - - - - -
-
-

Your download for {{ file_name }} should start automatically.

-

If it doesn't, please click here to download.

-
-
- - \ No newline at end of file diff --git a/Thunder/utils/bot_utils.py b/Thunder/utils/bot_utils.py index 10bf3c01..cf7c0e76 100644 --- a/Thunder/utils/bot_utils.py +++ b/Thunder/utils/bot_utils.py @@ -1,5 +1,9 @@ -# Thunder/utils/bot_utils.py +"""Link generation and the small bot actions the plugins share. +Builds canonical and shortened links, checks channel membership, and sends the +notifications that go to the owner or the log channel. +""" + import asyncio from typing import Any, Dict, Optional from urllib.parse import quote diff --git a/Thunder/utils/broadcast.py b/Thunder/utils/broadcast.py index 044dcd42..3311e23a 100644 --- a/Thunder/utils/broadcast.py +++ b/Thunder/utils/broadcast.py @@ -1,4 +1,8 @@ -# Thunder/utils/broadcast.py +"""Owner-only mass messaging, with per-recipient retry and progress reporting. + +Sends to users in batches, tolerates FloodWait, and drops recipients Telegram +says can no longer be reached. +""" import asyncio import os @@ -99,12 +103,10 @@ async def do_broadcast(): continue try: - success = False for attempt in range(3): try: await message.reply_to_message.copy(user_id) stats["success"] += 1 - success = True break except FloodWait as e: if attempt < 2: diff --git a/Thunder/utils/canonical_files.py b/Thunder/utils/canonical_files.py index 367171d1..fb58f561 100644 --- a/Thunder/utils/canonical_files.py +++ b/Thunder/utils/canonical_files.py @@ -1,3 +1,10 @@ +"""Canonical file records: one entry per file, keyed by a public hash. + +Storage and lookup layer for the files collection, plus a bounded in-process +cache and the ingest claim that stops two concurrent uploads of the same file +from writing two records. +""" + import asyncio import datetime import hashlib diff --git a/Thunder/utils/commands.py b/Thunder/utils/commands.py index d4831496..a53cb712 100644 --- a/Thunder/utils/commands.py +++ b/Thunder/utils/commands.py @@ -1,3 +1,5 @@ +"""Registers the bot command list with Telegram.""" + from pyrogram.types import BotCommand from Thunder.bot import StreamBot diff --git a/Thunder/utils/config_parser.py b/Thunder/utils/config_parser.py index d1bb0b4d..fad5caaf 100644 --- a/Thunder/utils/config_parser.py +++ b/Thunder/utils/config_parser.py @@ -1,13 +1,12 @@ -# Thunder/utils/config_parser.py +"""Collects MULTI_TOKEN1..N from the environment into client slots.""" import os -from typing import Dict, Optional +from typing import Dict from Thunder.utils.logger import logger class TokenParser: - def __init__(self, config_file: Optional[str] = None): + def __init__(self): self.tokens: Dict[int, str] = {} - self.config_file = config_file def parse_from_env(self) -> Dict[int, str]: try: diff --git a/Thunder/utils/custom_dl.py b/Thunder/utils/custom_dl.py index 22b0de46..fdf2538e 100644 --- a/Thunder/utils/custom_dl.py +++ b/Thunder/utils/custom_dl.py @@ -1,4 +1,8 @@ -# Thunder/utils/custom_dl.py +"""Streams a Telegram file over HTTP without buffering the whole thing. + +ByteStreamer yields byte ranges from the storage channel, which is what lets +the download routes answer Range requests and serve files far larger than RAM. +""" import asyncio from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, Optional diff --git a/Thunder/utils/database.py b/Thunder/utils/database.py index 6395a1b9..e3480d68 100644 --- a/Thunder/utils/database.py +++ b/Thunder/utils/database.py @@ -1,4 +1,8 @@ -# Thunder/utils/database.py +"""MongoDB access layer for users, tokens, bans and file records. + +Owns the collections, their unique indexes, and the duplicate-user recovery +that runs when an existing database predates the unique index on `id`. +""" import asyncio import datetime @@ -31,7 +35,7 @@ async def _deduplicate_users(self) -> None: {"$project": {"_id": "$doc_id"}} ] keep_ids = [] - async for doc in self.col.aggregate(pipeline): + async for doc in await self.col.aggregate(pipeline): keep_ids.append(doc["_id"]) if keep_ids: result = await self.col.delete_many({"_id": {"$nin": keep_ids}}) diff --git a/Thunder/utils/decorators.py b/Thunder/utils/decorators.py index b1209f19..fb9bf276 100644 --- a/Thunder/utils/decorators.py +++ b/Thunder/utils/decorators.py @@ -1,4 +1,8 @@ -# Thunder/utils/decorators.py +"""Guards that run before a user command: ban, token, force-subscribe. + +Each returns a truthy value to let the command continue, or sends its own +refusal and returns falsy so the caller stops. +""" import asyncio from pyrogram.errors import FloodWait diff --git a/Thunder/utils/file_properties.py b/Thunder/utils/file_properties.py index c83f7ae7..1e0dc77a 100644 --- a/Thunder/utils/file_properties.py +++ b/Thunder/utils/file_properties.py @@ -1,4 +1,8 @@ -# Thunder/utils/file_properties.py +"""Reads the fields the app needs out of a Pyrogram message. + +Every media type nests its metadata differently, so these helpers give the rest +of the code one shape to work with. +""" import asyncio from datetime import datetime as dt @@ -63,7 +67,6 @@ def get_fname(msg: Message) -> str: "sticker": "webp" } - # Check which attribute type the message has for attr, extension in media_types.items(): if getattr(msg, attr, None) is not None: ext = extension diff --git a/Thunder/utils/force_channel.py b/Thunder/utils/force_channel.py index 698ef180..3a036df4 100644 --- a/Thunder/utils/force_channel.py +++ b/Thunder/utils/force_channel.py @@ -1,4 +1,7 @@ -# Thunder/utils/force_channel.py +"""Blocking force-subscribe: a user must join the configured channel first. + +Answers with a join button and a re-check callback when membership is missing. +""" import asyncio diff --git a/Thunder/utils/human_readable.py b/Thunder/utils/human_readable.py index 0a7ee460..c5ab7ddd 100644 --- a/Thunder/utils/human_readable.py +++ b/Thunder/utils/human_readable.py @@ -1,4 +1,4 @@ -# Thunder/utils/human_readable.py +"""Byte and duration formatting for display.""" from Thunder.utils.logger import logger diff --git a/Thunder/utils/keepalive.py b/Thunder/utils/keepalive.py index d7089c04..93069d11 100644 --- a/Thunder/utils/keepalive.py +++ b/Thunder/utils/keepalive.py @@ -1,4 +1,4 @@ -# Thunder/utils/keepalive.py +"""Periodically pings the public URL so a host that idles on traffic stays up.""" import asyncio import aiohttp diff --git a/Thunder/utils/logger.py b/Thunder/utils/logger.py index 6609a39b..7e56e400 100644 --- a/Thunder/utils/logger.py +++ b/Thunder/utils/logger.py @@ -1,4 +1,7 @@ -# Thunder/utils/logger.py +"""The shared logger: non-blocking queue, rotating file, and console output. + +Handlers write from a listener thread so logging never blocks the event loop. +""" import logging from logging.handlers import RotatingFileHandler, QueueHandler, QueueListener diff --git a/Thunder/utils/messages.py b/Thunder/utils/messages.py index feb8f040..95dfb5b4 100644 --- a/Thunder/utils/messages.py +++ b/Thunder/utils/messages.py @@ -1,14 +1,16 @@ -# Thunder/utils/messages.py +"""Every user-facing string, grouped by where it appears. -# ===================================================================================== -# ====== ERROR MESSAGES ====== -# ===================================================================================== +Kept in one module so wording and formatting can be changed without touching +the handlers that send them. +""" -# ------ General Errors ------ +# ERROR MESSAGES + +# General Errors MSG_ERROR_GENERIC = "⚠️ **Oops!** Something went wrong. Please try again. If the issue persists, contact support." MSG_ERROR_USER_INFO = "❗ **User Not Found:** Couldn't find user. Please check the ID or Username." -# ------ User Input & Validation Errors ------ +# User Input & Validation Errors MSG_INVALID_USER_ID = "❌ **Invalid User ID:** Please provide a numeric user ID." MSG_ERROR_START_BOT = "⚠️ You need to start the bot in private first to use this command.\n👉 [Click here]({invite_link}) to start a private chat." MSG_ERROR_REPLY_FILE = "⚠️ Please use the /link command in reply to a file." @@ -17,10 +19,10 @@ MSG_ERROR_NUMBER_RANGE = "⚠️ **Please specify a number between 1 and {max_files}.**" MSG_ERROR_DM_FAILED = "⚠️ I couldn't send you a Direct Message. Please start the bot first." -# ------ File & Media Errors ------ +# File & Media Errors MSG_ERROR_PROCESSING_MEDIA = "⚠️ **Oops!** Something went wrong while processing your media. Please try again. If the issue persists, contact support." -# ------ Admin Action Errors (Ban, Auth, etc.) ------ +# Admin Action Errors (Ban, Auth, etc.) MSG_AUTHORIZE_FAILED = ( "❌ **Authorization Failed:** " "Could not authorize user `{user_id}`." @@ -37,12 +39,11 @@ MSG_SHELL_ERROR = """**❌ Shell Command Error ❌**
{error}
""" -# ------ System & Bot Errors ------ +# System & Bot Errors MSG_ERROR_NOT_ADMIN = "⚠️ **Admin Required:** I need admin privileges to work here." MSG_DC_INVALID_USAGE = "🤔 **Invalid Usage:** Please reply to a user's message or a media file to get DC info." MSG_DC_ANON_ERROR = "😥 **Cannot Get Your DC Info:** Unable to identify you. This command might not work for anonymous users." MSG_DC_FILE_ERROR = "⚙️ **Error Getting File DC Info:** Could not fetch details. File might be inaccessible." -MSG_STATS_ERROR = "❌ **Stats Error:** Could not retrieve system statistics." MSG_STATUS_ERROR = "❌ **Status Error:** Could not retrieve system status." MSG_DB_ERROR = "❌ **Database Error:** Could not retrieve user count." MSG_CRITICAL_ERROR = ( @@ -51,11 +52,9 @@ "Please investigate immediately! (ID: {error_id})" ) -# ===================================================================================== -# ====== ADMIN MESSAGES ====== -# ===================================================================================== +# ADMIN MESSAGES -# ------ Ban/Unban ------ +# Ban/Unban MSG_DECORATOR_BANNED = "You are currently banned and cannot use this bot.\nReason: {reason}\nBanned on: {ban_time}" MSG_BAN_USAGE = "⚠️ **Usage:** /ban [user_id] [reason]" MSG_CANNOT_BAN_OWNER = "❌ **Cannot ban an owner.**" @@ -72,7 +71,7 @@ MSG_CHANNEL_UNBANNED = "✅ **Channel {channel_id} has been unbanned.**" MSG_CHANNEL_NOT_BANNED = "ℹ️ **Channel {channel_id} was not found in the ban list.**" -# ------ Token & Authorization ------ +# Token & Authorization MSG_AUTHORIZE_USAGE = "🔑 **Usage:** `/authorize `" MSG_DEAUTHORIZE_USAGE = "🔒 **Usage:** `/deauthorize `" MSG_AUTHORIZE_SUCCESS = ( @@ -94,7 +93,7 @@ • Date: `{auth_time}`\n\n""" MSG_ADMIN_AUTH_LIST_HEADER = "🔐 **Authorized Users List**\n\n" -# ------ Shell Commands ------ +# Shell Commands MSG_SHELL_USAGE = ( "Usage:\n" "/shell \n\n" @@ -108,7 +107,7 @@ MSG_SHELL_OUTPUT_STDERR = "[stderr]:\n
{error}
" MSG_SHELL_NO_OUTPUT = "✅ Command Executed: No output." -# ------ Admin View & Control ------ +# Admin View & Control MSG_WORKLOAD_ITEM = " {bot_name}: {load}\n" MSG_ADMIN_RESTART_DONE = "✅ **Restart Successful!**" @@ -118,9 +117,7 @@ MSG_LOG_FILE_EMPTY = "ℹ️ **Log File Empty:** No data found in the log file." MSG_LOG_FILE_MISSING = "⚠️ **Log File Missing:** Could not find the log file." -# ===================================================================================== -# ====== BUTTON TEXTS (User-facing) ====== -# ===================================================================================== +# BUTTON TEXTS (User-facing) MSG_BUTTON_STREAM_NOW = "🖥️ Stream" MSG_BUTTON_DOWNLOAD = "🚀 Download" @@ -134,9 +131,7 @@ MSG_BUTTON_CLOSE = "✖ Close" -# ===================================================================================== -# ====== COMMAND RESPONSES (User-facing) ====== -# ===================================================================================== +# COMMAND RESPONSES (User-facing) MSG_WELCOME = ( "🌟 **Welcome, {user_name}!** 🌟\n\n" @@ -197,7 +192,7 @@ "💖 If you find me useful, please consider sharing me with your friends!" ) -# ------ Ping ------ +# Ping MSG_PING_START = "🛰️ **Pinging...** Please wait." MSG_PING_RESPONSE = ( "☁️ **PONG! Bot is Online!** ⚡\n\n" @@ -205,7 +200,7 @@ "> 🤖 **Bot Status:** `Active`" ) -# ------ DC Info ------ +# DC Info MSG_DC_USER_INFO = ( "📍 **Information**\n" "> 👤 **User:** [{user_name}](tg://user?id={user_id})\n" @@ -223,7 +218,7 @@ MSG_DC_UNKNOWN = "Unknown" -# ------ File Link Generation ------ +# File Link Generation MSG_DM_SINGLE_PREFIX = "📬 **From {chat_title}**\n" MSG_LINKS = ( "✨ **Your Links are Ready!** ✨\n\n" @@ -234,9 +229,7 @@ "⌛️ **Note: Links remain active while the bot is running and the file is accessible.**" ) -# ===================================================================================== -# ====== USER NOTIFICATIONS ====== -# ===================================================================================== +# USER NOTIFICATIONS MSG_NEW_USER = ( "✨ **New User Alert!** ✨\n" @@ -245,11 +238,9 @@ ) MSG_COMMUNITY_CHANNEL = "📢 **{channel_title}:** 🔒 Join this channel to use the bot." -# ===================================================================================== -# ====== PROCESSING MESSAGES ====== -# ===================================================================================== +# PROCESSING MESSAGES -# ------ General File Processing ------ +# General File Processing MSG_PROCESSING_REQUEST = "⏳ **Processing your request...**" MSG_PROCESSING_FILE = "⏳ **Processing your file...**" MSG_NEW_FILE_REQUEST = ( @@ -259,16 +250,14 @@ "🖥️ **Stream:** `{stream_link}`" ) -# ------ Batch Processing ------ +# Batch Processing MSG_PROCESSING_BATCH = "♻️ **Processing Batch {batch_number}/{total_batches}** ({file_count} files)" MSG_PROCESSING_STATUS = "📊 **Processing Files:** {processed}/{total} complete, {failed} failed" MSG_BATCH_LINKS_READY = "🔗 Here are your {count} download links:" MSG_DM_BATCH_PREFIX = "📬 **Batch Links from {chat_title}**\n" MSG_PROCESSING_RESULT = "✅ **Process Complete:** {processed}/{total} files processed successfully, {failed} failed" -# ===================================================================================== -# ====== BROADCAST MESSAGES ====== -# ===================================================================================== +# BROADCAST MESSAGES MSG_BROADCAST_START = "📣 **Starting Broadcast...**\n\n> ⏳ Please wait for completion." MSG_BROADCAST_COMPLETE = ( @@ -289,18 +278,14 @@ "**Note:** Reply to the message you want to broadcast." ) -# ===================================================================================== -# ====== PERMISSION MESSAGES ====== -# ===================================================================================== +# PERMISSION MESSAGES MSG_ERROR_UNAUTHORIZED = "You are not authorized to view this information." MSG_ERROR_BROADCAST_RESTART = "Please use the /broadcast command to start a new broadcast." MSG_ERROR_BROADCAST_INSTRUCTION = "To start a new broadcast, use the /broadcast command and reply to the message you want to broadcast." MSG_ERROR_CALLBACK_UNSUPPORTED = "This button is not active or no longer supported." -# ===================================================================================== -# ====== RATE LIMITING MESSAGES ====== -# ===================================================================================== +# RATE LIMITING MESSAGES MSG_RATE_LIMIT_QUEUE_PRIORITY = ( "⚡ You're in the **Priority Queue!**\n\n" @@ -322,9 +307,7 @@ ) -# ===================================================================================== -# ====== FILE TYPE DESCRIPTIONS ====== -# ===================================================================================== +# FILE TYPE DESCRIPTIONS MSG_FILE_TYPE_DOCUMENT = "📄 Document" MSG_FILE_TYPE_PHOTO = "🖼️ Photo" MSG_FILE_TYPE_VIDEO = "🎬 Video" @@ -335,9 +318,7 @@ MSG_FILE_TYPE_VIDEO_NOTE = "📹 Video Note" MSG_FILE_TYPE_UNKNOWN = "❓ Unknown File Type" -# ===================================================================================== -# ====== SYSTEM & STATUS MESSAGES ====== -# ===================================================================================== +# SYSTEM & STATUS MESSAGES MSG_SYSTEM_STATUS = ( "✅ **System Status:** Operational\n\n" @@ -349,7 +330,7 @@ "> ♻️ **Version:** `{version}`" ) -# ------ Speedtest Messages ------ +# Speedtest Messages MSG_SPEEDTEST_INIT = "🚀 **Running Speed Test...**" MSG_SPEEDTEST_ERROR = "❌ **Speed Test Failed!**\n\n> Unable to complete the speed test. Please try again later." MSG_SPEEDTEST_RESULT = ( diff --git a/Thunder/utils/rate_limiter.py b/Thunder/utils/rate_limiter.py index e7ca1176..aadc2eae 100644 --- a/Thunder/utils/rate_limiter.py +++ b/Thunder/utils/rate_limiter.py @@ -1,4 +1,8 @@ -# Thunder/utils/rate_limiter.py +"""Two-tier request queues: owners bypass, authorized users get priority. + +Counts per-user and global requests inside a sliding window and re-queues a +request that arrives over the limit instead of rejecting it. +""" import time import math diff --git a/Thunder/utils/render_template.py b/Thunder/utils/render_template.py index 5c6ef1a1..15435b21 100644 --- a/Thunder/utils/render_template.py +++ b/Thunder/utils/render_template.py @@ -1,4 +1,4 @@ -# Thunder/utils/render_template.py +"""Renders the HTML player page from a stored file record.""" import asyncio import urllib.parse @@ -21,25 +21,18 @@ optimized=True ) -async def render_media_page(file_name: str, src: str, requested_action: str | None = None) -> str: +async def render_media_page(file_name: str, src: str) -> str: # NOTE: src must be a pre-encoded URL. Templates use |safe to avoid double-encoding. - if requested_action == 'stream': - template = template_env.get_template('req.html') - context = { - 'heading': f"View {file_name}", - 'file_name': file_name, - 'src': f"{src}?disposition=inline" - } - else: - template = template_env.get_template('dl.html') - context = { - 'file_name': file_name, - 'src': src - } + template = template_env.get_template('req.html') + context = { + 'heading': f"View {file_name}", + 'file_name': file_name, + 'src': f"{src}?disposition=inline" + } return await template.render_async(**context) -async def render_page(message_id: int, secure_hash: str, requested_action: str | None = None) -> str: +async def render_page(message_id: int, secure_hash: str) -> str: try: try: message = await StreamBot.get_messages(chat_id=int(Var.BIN_CHANNEL), message_ids=message_id) @@ -58,7 +51,7 @@ async def render_page(message_id: int, secure_hash: str, requested_action: str | quoted_filename = urllib.parse.quote(file_name.replace('/', '_'), safe="") src = urllib.parse.urljoin(Var.URL, f'{secure_hash}{message_id}/{quoted_filename}') - return await render_media_page(file_name, src, requested_action) + return await render_media_page(file_name, src) except Exception as e: logger.error( f"Error in render_page for message_id {message_id} and hash {secure_hash}: {e}", diff --git a/Thunder/utils/shortener.py b/Thunder/utils/shortener.py index 64abe840..aeee395c 100644 --- a/Thunder/utils/shortener.py +++ b/Thunder/utils/shortener.py @@ -1,4 +1,8 @@ -# Thunder/utils/shortener.py +"""URL shortener plugins: one per provider, chosen by the configured site. + +``shorten`` returns the original URL when no plugin matches or the provider +fails, so a broken shortener never breaks link generation. +""" import asyncio import cloudscraper diff --git a/Thunder/utils/speedtest.py b/Thunder/utils/speedtest.py index bdd94cc3..21573676 100644 --- a/Thunder/utils/speedtest.py +++ b/Thunder/utils/speedtest.py @@ -1,4 +1,4 @@ -# Thunder/utils/speedtest.py +"""Speed test via speedtest-cli, rendering the result as an image.""" import asyncio from typing import Optional, Tuple, Dict, Any diff --git a/Thunder/utils/time_format.py b/Thunder/utils/time_format.py index 6900312d..7e5c50c0 100644 --- a/Thunder/utils/time_format.py +++ b/Thunder/utils/time_format.py @@ -1,4 +1,4 @@ -# Thunder/utils/time_format.py +"""Human-readable durations ("2h 15m").""" from Thunder.utils.logger import logger diff --git a/Thunder/utils/tokens.py b/Thunder/utils/tokens.py index 818d3619..540e1209 100644 --- a/Thunder/utils/tokens.py +++ b/Thunder/utils/tokens.py @@ -1,4 +1,8 @@ -# Thunder/utils/tokens.py +"""Token gate: who may generate links while TOKEN_ENABLED is on. + +Issues, validates and expires access tokens, and tracks the separate list of +permanently authorized users. +""" import secrets from datetime import datetime, timedelta, timezone diff --git a/Thunder/vars.py b/Thunder/vars.py index c5e439aa..646ffb22 100644 --- a/Thunder/vars.py +++ b/Thunder/vars.py @@ -1,4 +1,8 @@ -# Thunder/vars.py +"""Environment configuration, validated at import. + +A missing requirement stops startup here rather than failing later, so any +import of this module implies usable settings. +""" import os diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..76c0a735 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,20 @@ +# Tool configuration only: the app is not a distributable package, so there is +# no [project] table. One config file for both tools. + +[tool.ruff] +line-length = 120 +target-version = "py313" + +[tool.ruff.lint] +# E4 stays out on purpose: __main__.py imports after creating the event loop, +# which Pyrogram requires, so its E402 findings are all intentional. +select = ["E7", "E9", "F"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +filterwarnings = [ + "ignore:There is no current event loop:DeprecationWarning", +] +addopts = "-ra" diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index c7b3269d..00000000 --- a/pytest.ini +++ /dev/null @@ -1,7 +0,0 @@ -[pytest] -testpaths = tests -asyncio_mode = auto -asyncio_default_fixture_loop_scope = function -filterwarnings = - ignore:There is no current event loop:DeprecationWarning -addopts = -ra diff --git a/requirements-dev.txt b/requirements-dev.txt index bf51dd49..b222cdad 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,3 +1,7 @@ -r requirements.txt pytest pytest-asyncio +# Lint gate (config in pyproject.toml), run locally and in CI. +ruff +# tests/test_ci_workflow.py parses the workflow files to check their invariants. +pyyaml diff --git a/requirements.txt b/requirements.txt index fdba46f3..08b84617 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,8 +7,7 @@ pymongo psutil python-dotenv speedtest-cli -tgcrypto -# uvloop cannot be built on Windows, so it is only installed on other -# platforms. The bot falls back to the standard asyncio loop when it is -# missing. -uvloop==0.21.0; sys_platform != "win32" and sys_platform != "cygwin" +# Fork provides cp313/cp314 wheels (avoids C toolchain at build time) and imports as "tgcrypto". +tgcrypto-pyrofork +# uvloop is Unix-only; bot falls back to standard asyncio on Windows. +uvloop>=0.22.1; sys_platform != "win32" and sys_platform != "cygwin" diff --git a/tests/test_ci_workflow.py b/tests/test_ci_workflow.py new file mode 100644 index 00000000..81ec061f --- /dev/null +++ b/tests/test_ci_workflow.py @@ -0,0 +1,258 @@ +"""The CI workflow must keep the properties its gate depends on. + +Each check below stands for a failure this project has had or could have had: + +* a build job without ``needs: [test]`` publishes an image from a red main -- + which is exactly what dockerize.yml did before the two files were merged; +* a login step reachable from a pull request asks for ``secrets.DOCKER_TOKEN`` + on fork PRs, which never receive secrets, so every fork PR fails; +* an action referenced by a tag can be repointed at new code by whoever owns it; +* with a floating requirements.txt and no weekly run, a bad upstream release is + found by a user rather than by CI. + +None of this is visible to a code test, so it is pinned here instead. +""" +import re +from pathlib import Path + +import yaml + +REPO = Path(__file__).resolve().parent.parent +WORKFLOWS = REPO / ".github" / "workflows" +PINNED_ACTION = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") +PUSH_EVENT = "github.event_name == 'push'" + + +def load(path: Path): + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def workflow(): + return load(WORKFLOWS / "tests.yml") + + +def triggers(doc): + # PyYAML implements YAML 1.1, where the bare key `on` parses as boolean True. + return doc.get("on", doc.get(True, {})) or {} + + +def uses_of(doc, job, prefix): + return [step for step in doc["jobs"][job]["steps"] + if str(step.get("uses", "")).startswith(prefix)] + + +def test_no_other_workflow_can_publish_an_image(): + """A second publisher is how main went red and shipped anyway. + + Any workflow other than the gated one that builds or pushes an image is a + regression, whether it is dockerize.yml returning or a new one appearing. + """ + others = [entry for entry in WORKFLOWS.iterdir() if entry.name != "tests.yml"] + publishers = [ + entry.name for entry in others + if any(marker in entry.read_text(encoding="utf-8") + for marker in ("docker/build-push-action", "docker push")) + ] + assert publishers == [], f"{publishers} can publish an image outside the gated workflow" + + +def test_nothing_publishes_before_the_tests_pass(): + doc = workflow() + needs = doc["jobs"]["build"].get("needs") or [] + needs = [needs] if isinstance(needs, str) else needs + assert "test" in needs, "the image must not build unless the tests passed" + + logins = uses_of(doc, "build", "docker/login-action") + assert logins, "pushing needs a login step" + for step in logins: + assert PUSH_EVENT in step.get("if", ""), "no secret may be requested on a pull request" + + builds = uses_of(doc, "build", "docker/build-push-action") + assert builds, "the build job must build something" + for step in builds: + push = step.get("with", {}).get("push") + if push in (None, "false", False): + continue + # A publish is either gated on the event directly, or the whole step is. + gated = PUSH_EVENT in str(push) or PUSH_EVENT in str(step.get("if", "")) + assert gated, f"a publish is not gated on a push event: {step.get('name')}" + + +def test_a_publish_is_reached_only_after_the_image_has_been_run(): + """Test, then publish -- the other order ships a broken image. + + The step that publishes used to come before the smoke test, so a failure + would already have pushed the image tagged latest to Docker Hub. Docker's own + "test before push" pattern is build-and-load, test, then push. + """ + steps = workflow()["jobs"]["build"]["steps"] + + smoke = [i for i, step in enumerate(steps) + if "docker run" in str(step.get("run", ""))] + assert smoke, "the image is never run, so nothing is tested" + first_smoke = min(smoke) + + for i, step in enumerate(steps): + publishes = (step.get("with") or {}).get("push") in (True, "true") or \ + str((step.get("with") or {}).get("push", "")).startswith("${{") and \ + "== 'push'" in str((step.get("with") or {}).get("push")) + if publishes: + assert i > first_smoke, ( + f"step {i} ({step.get('name')}) publishes before the smoke test at " + f"{first_smoke}, so a broken image can reach latest" + ) + + +def test_actions_are_pinned_to_commits(): + text = (WORKFLOWS / "tests.yml").read_text(encoding="utf-8") + for reference in re.findall(r"uses:\s*(\S+)", text): + assert PINNED_ACTION.match(reference), f"{reference} can be repointed; pin a commit SHA" + + +def test_jobs_are_bounded_and_read_only(): + doc = workflow() + assert doc["permissions"] == {"contents": "read"} + for name, job in doc["jobs"].items(): + assert "github.repository ==" in job.get("if", ""), f"{name} would also run in forks" + assert job.get("timeout-minutes"), f"{name} can hang until the 6-hour limit" + + +def test_the_suite_runs_on_both_operating_systems(): + matrix = workflow()["jobs"]["test"]["strategy"]["matrix"] + assert any(os_name.startswith("ubuntu") for os_name in matrix["os"]), matrix["os"] + assert any(os_name.startswith("windows") for os_name in matrix["os"]), ( + "the uvloop marker and update.py's chmod fallback only run on Windows" + ) + assert "3.13" in [str(value) for value in matrix["python-version"]] + + +def test_the_documented_python_range_is_actually_tested(): + """README says 3.13+; a floating dependency can quietly drop the newer one.""" + matrix = workflow()["jobs"]["test"]["strategy"]["matrix"] + tested = {str(value) for value in matrix["python-version"]} + tested |= {str(entry["python-version"]) for entry in matrix.get("include", [])} + assert "3.14" in tested, ( + "3.14 was deferred only until uvloop shipped cp314 wheels, which it now " + "does; the range is documented, so it is tested" + ) + + +def test_a_weekly_run_guards_the_floating_dependencies(): + schedule = triggers(workflow()).get("schedule") + assert schedule and schedule[0].get("cron"), ( + "requirements.txt floats on purpose, so a weekly run against fresh " + "dependencies is the only thing that catches a bad release" + ) + + +def test_duplicate_pull_request_runs_are_cancelled(): + concurrency = workflow()["concurrency"] + assert "pull_request" in str(concurrency["cancel-in-progress"]), ( + "cancelling a run that is mid-publish is worse than waiting for it" + ) + + +def test_attestations_are_built_with_a_driver_that_supports_them(): + """`provenance: mode=max` needs the containerd store on the docker driver. + + The action passes --attest whenever the input is set, and the default docker + driver cannot write an image index to the classic image store, so the build + fails outright on a stock ubuntu runner. A container-driver builder supports + attestations regardless of the daemon's store. + """ + doc = workflow() + steps = doc["jobs"]["build"]["steps"] + names = [str(step.get("uses", "")) for step in steps] + + asserted = [step for step in steps + if step.get("with", {}).get("provenance") not in (None, "false", False)] + if not asserted: + return # opted out of attestations; nothing to support + + assert any(name.startswith("docker/setup-buildx-action@") for name in names), ( + "an explicit provenance attestation requires a container-driver builder" + ) + + +def test_the_built_image_is_actually_run(): + """A build that succeeds is not proof the image starts. + + A missing dependency or a broken import still produces a valid image, so the + published artifact is executed once before it is trusted. + """ + steps = workflow()["jobs"]["build"]["steps"] + smoke = [step for step in steps if "docker run" in str(step.get("run", ""))] + assert smoke, "the image is built and pushed without ever being started" + + build = [step for step in steps + if str(step.get("uses", "")).startswith("docker/build-push-action")] + assert build, "the smoke test needs an image to run" + with_ = build[0].get("with", {}) + + # Thunder.vars validates its configuration at import and raises without it, + # and the image ships no config.env (deliberately). The smoke test must + # therefore supply placeholders, or it fails on a perfectly good image. + smoke_run = " ".join(str(step.get("run", "")) for step in smoke) + smoke_env = {} + for step in smoke: + smoke_env.update(step.get("env", {}) or {}) + supplied = " ".join(smoke_env.values()) + smoke_run + for required in ("API_ID", "API_HASH", "BOT_TOKEN", "BIN_CHANNEL", "DATABASE_URL"): + assert required in supplied, ( + f"the smoke test imports the entry point but never sets {required}; " + "Thunder.vars raises without it and the step would fail on a good image" + ) + + # The image under test is the one the build step loaded, not one pulled back + # from a registry: the tested build and the publishing build are separate + # steps, and only the second one pushes. + assert with_.get("load") in (True, "true"), ( + "the image under test must be loaded into the daemon, or `docker run` " + "finds nothing before any pull" + ) + assert with_.get("push") in (None, "false", False), \ + "the build that gets tested must not also be the one that publishes" + + # Any step output the smoke test interpolates must come from a step that + # declares the matching id, or it silently expands to nothing. + id_values = {step.get("id") for step in steps} + referenced = set() + for step in smoke: + for value in list(step.get("env", {}).values()) + [str(step.get("run", ""))]: + referenced |= set(re.findall(r"steps\.([A-Za-z0-9_-]+)\.", str(value))) + assert referenced <= id_values, ( + f"interpolates steps.{sorted(referenced - id_values)} but no such id exists" + ) + + +def test_every_advertised_command_has_a_handler(): + """Guards the invariant test_plugin_registration.py checks end to end. + + Cheap and structural: it fails at review time rather than after a boot. + """ + import ast + + commands_src = (REPO / "Thunder" / "utils" / "commands.py").read_text(encoding="utf-8") + advertised = set() + for node in ast.walk(ast.parse(commands_src)): + if isinstance(node, ast.Assign) and any( + getattr(t, "id", "") == "command_descriptions" for t in node.targets): + advertised = {k.value for k in node.value.keys} + assert advertised, "the command table could not be read" + + plugins = (REPO / "Thunder" / "bot" / "plugins").glob("*.py") + registered = set() + for plugin in plugins: + for match in re.findall(r'command\(\s*"([^"]+)"', plugin.read_text(encoding="utf-8")): + registered.add(match) + + assert advertised <= registered, \ + f"advertised to Telegram but never registered: {sorted(advertised - registered)}" + + +def test_dependabot_only_tracks_actions(): + doc = load(REPO / ".github" / "dependabot.yml") + ecosystems = {update["package-ecosystem"] for update in doc["updates"]} + assert ecosystems == {"github-actions"}, ( + "app dependencies float by policy, so only the pinned actions need updates" + ) diff --git a/tests/test_database_dedup.py b/tests/test_database_dedup.py new file mode 100644 index 00000000..b20002e9 --- /dev/null +++ b/tests/test_database_dedup.py @@ -0,0 +1,83 @@ +"""Verify _deduplicate_users awaits AsyncCollection.aggregate coroutine on DuplicateKeyError.""" +from pymongo.errors import DuplicateKeyError + +from Thunder.utils.database import Database + + +class FakeCursor: + """Mirrors AsyncCommandCursor: async-iterable once awaited.""" + + def __init__(self, docs): + self._docs = docs + + def __aiter__(self): + async def gen(): + for doc in self._docs: + yield doc + return gen() + + +class FakeDeleteResult: + def __init__(self, deleted_count): + self.deleted_count = deleted_count + + +class FakeCollection: + """Mirrors the pymongo async shapes this path uses.""" + + def __init__(self, keep_ids=None): + self._keep_ids = keep_ids or [] + self.deleted_filter = None + + async def aggregate(self, pipeline): + return FakeCursor([{"_id": doc_id} for doc_id in self._keep_ids]) + + async def delete_many(self, filter_): + self.deleted_filter = filter_ + return FakeDeleteResult(len(self._keep_ids)) + + async def create_index(self, *args, **kwargs): + return "index_name" + + +class RecoveryCollection(FakeCollection): + """Fails the unique-id index once, like a collection holding duplicates.""" + + def __init__(self, keep_ids): + super().__init__(keep_ids) + self.failed_once = False + + async def create_index(self, *args, **kwargs): + if not self.failed_once and args == ("id",) and kwargs.get("unique"): + self.failed_once = True + raise DuplicateKeyError("duplicate key error") + return "index_name" + + +def make_db(users_col): + """A Database with no client: only the collection attributes are used.""" + db = Database.__new__(Database) + db.col = users_col + for name in ("banned_users_col", "banned_channels_col", "token_col", + "authorized_users_col", "restart_message_col", "files_col", + "file_ingest_locks_col"): + setattr(db, name, FakeCollection()) + return db + + +async def test_deduplicate_users_awaits_the_aggregate_cursor(): + col = FakeCollection(keep_ids=[10, 20]) + db = make_db(col) + + await db._deduplicate_users() + + assert col.deleted_filter == {"_id": {"$nin": [10, 20]}} + + +async def test_ensure_indexes_recovers_from_duplicate_keys(): + """Verify ensure_indexes recovers from DuplicateKeyError by running deduplication.""" + col = RecoveryCollection(keep_ids=[10, 20]) + db = make_db(col) + + assert await db.ensure_indexes() is True + assert col.deleted_filter == {"_id": {"$nin": [10, 20]}} diff --git a/tests/test_deployment_entrypoints.py b/tests/test_deployment_entrypoints.py new file mode 100644 index 00000000..65831efb --- /dev/null +++ b/tests/test_deployment_entrypoints.py @@ -0,0 +1,25 @@ +"""Deployment entry points that only a hosting platform reads. + +Nothing in Thunder/ imports these, so no test failure or grep would notice them +going away -- but deleting one breaks a documented deployment while the suite +stays green. Procfile in particular is required by Heroku's Python buildpack, +which has no default web process. +""" +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent + + +def test_procfile_declares_the_web_process(): + procfile = (REPO / "Procfile").read_text(encoding="utf-8") + assert procfile.startswith("web:"), "Heroku's buildpack needs a web process type" + assert "python -m Thunder" in procfile, "the app's only entry point" + + +def test_platform_files_consumed_at_deploy_time_still_exist(): + for name in ("Procfile", "heroku.yml", ".python-version", "requirements.txt"): + target = REPO / name + assert target.is_file(), f"{name} is read by the deploy platform, not by our code" + + assert (REPO / ".python-version").read_text(encoding="utf-8").strip(), \ + "Heroku reads this to pick the interpreter" diff --git a/tests/test_plugin_registration.py b/tests/test_plugin_registration.py new file mode 100644 index 00000000..30e597d8 --- /dev/null +++ b/tests/test_plugin_registration.py @@ -0,0 +1,137 @@ +"""Importing the plugins must actually register command handlers. + +The four files in Thunder/bot/plugins/ are loaded by path at startup, and each +registers its handlers as a side effect of being imported. Two failures are +invisible to an ordinary import check: + +* a plugin raises while importing -- import_plugins logs it and carries on, so + the bot boots with that plugin's commands silently missing; +* a plugin imports fine but no longer registers anything, because its + decorators were dropped. From the outside those look identical. + +Both need the loop to run: Dispatcher.add_handler only *schedules* registration, +so counting handlers synchronously always reports the conversation handler alone. + +The check runs in a subprocess for the same reason Thunder starts the way it +does: importing Thunder.__main__ installs the uvloop policy and sets a current +event loop, and neither belongs in the test process. The subprocess also gets +the production import order, where Thunder.__main__ comes before Thunder.bot so +the dispatcher binds to the loop the app actually runs. +""" +import json +import os +import subprocess +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +PLUGINS_DIR = REPO / "Thunder" / "bot" / "plugins" +MARKER = "REGISTRATION_RESULT=" + +# Var validates at import and raises without these, and config.env is absent in +# CI. Set them explicitly rather than inheriting a developer's real config, +# which would hide a missing requirement. +PLACEHOLDER_ENV = { + "API_ID": "123456", + "API_HASH": "0" * 32, + "BOT_TOKEN": "123456:AA" + "x" * 30, + "BIN_CHANNEL": "-1001234567890", + "OWNER_ID": "1", + "DATABASE_URL": "mongodb://localhost:27017/thunder_test", +} + +PROBE = f''' +import asyncio, json, sys +sys.path.insert(0, ".") + +# Production order: __main__ creates the loop, then importing Thunder.bot binds +# the dispatcher to it. +import Thunder.__main__ as entry +from Thunder.bot import StreamBot +from Thunder.utils.commands import get_commands + + +def count(dispatcher): + return sum(len(group) for group in dispatcher.groups.values()) + + +def commands_in(filt, depth=0): + found = set() + if filt is None or depth > 8: + return found + found.update(getattr(filt, "commands", None) or ()) + found |= commands_in(getattr(filt, "base", None), depth + 1) + found |= commands_in(getattr(filt, "other", None), depth + 1) + for extra in getattr(filt, "filters", None) or (): + found |= commands_in(extra, depth + 1) + return found + + +async def main(): + dispatcher = StreamBot.dispatcher + before = count(dispatcher) + imported = await entry.import_plugins() + + # One task per handler, plus the locks they take; wait for the count to stop + # moving rather than guessing a number of ticks. + stable = 0 + previous = -1 + for _ in range(500): + await asyncio.sleep(0) + now = count(dispatcher) + stable = stable + 1 if now == previous else 0 + previous = now + if stable >= 3: + break + + registered = set() + for group in dispatcher.groups.values(): + for handler in group: + registered |= commands_in(getattr(handler, "filters", None)) + + advertised = {{command.command for command in get_commands()}} + print("{MARKER}" + json.dumps({{ + "imported": imported, + "handlers_before": before, + "handlers_after": count(dispatcher), + "advertised": sorted(advertised), + "missing": sorted(advertised - registered), + }})) + + +entry.LOOP.run_until_complete(main()) +''' + + +def run_probe(): + env = {**os.environ, **PLACEHOLDER_ENV} + result = subprocess.run([sys.executable, "-c", PROBE], cwd=REPO, env=env, + capture_output=True, timeout=600, + encoding="utf-8", errors="replace") + assert result.returncode == 0, ( + "the plugin import crashed:\n" + (result.stderr or result.stdout)[-2000:] + ) + line = next((ln for ln in (result.stdout or "").splitlines() if ln.startswith(MARKER)), None) + assert line, "the probe produced no result:\n" + (result.stdout or result.stderr)[-2000:] + return json.loads(line[len(MARKER):]) + + +def test_importing_the_plugins_registers_every_advertised_command(): + expected_plugins = len(list(PLUGINS_DIR.glob("*.py"))) + assert expected_plugins, "no plugin files found, so this test proves nothing" + + outcome = run_probe() + + assert outcome["imported"] == expected_plugins, ( + f"only {outcome['imported']} of {expected_plugins} plugins imported; a " + "failure is logged and the bot then boots with that plugin's commands " + "silently missing" + ) + + registered = outcome["handlers_after"] - outcome["handlers_before"] + assert registered > 0, "the plugins registered no handlers at all" + + assert outcome["advertised"], "no commands are advertised, so this proves nothing" + assert outcome["missing"] == [], ( + f"advertised to Telegram but unhandled: {outcome['missing']}" + ) diff --git a/tests/test_render_template.py b/tests/test_render_template.py new file mode 100644 index 00000000..f422a31a --- /dev/null +++ b/tests/test_render_template.py @@ -0,0 +1,19 @@ +"""Verify render_media_page embeds filename and inline disposition source URL.""" +from pathlib import Path + +from jinja2 import FileSystemLoader + +from Thunder.utils import render_template + +TEMPLATE_DIR = Path(__file__).resolve().parent.parent / "Thunder" / "template" + + +async def test_render_media_page_returns_player_with_inline_source(monkeypatch): + """Point template loader at repo template dir so test is location-independent.""" + monkeypatch.setattr(render_template.template_env, "loader", FileSystemLoader(str(TEMPLATE_DIR))) + + src = "https://example.invalid/f/abc123/clip.mp4" + page = await render_template.render_media_page("clip.mp4", src) + + assert "clip.mp4" in page + assert f"{src}?disposition=inline" in page diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.py new file mode 100644 index 00000000..79ef66d1 --- /dev/null +++ b/tests/test_repo_hygiene.py @@ -0,0 +1,68 @@ +"""Verify .gitignore keeps credentials and local state out of a commit. + +update.py no longer stages anything, so the risk is a person running `git add -A` +in a working checkout, and `git commit -a` on modified tracked files. Both are +ordinary things to do, and `config.env` must not be among what they pick up. +""" +import os +import shutil +import subprocess +import tempfile +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent + +# Isolate from ambient user or system git configuration. +GIT_ENV = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} + + +def git(repo: Path, *args: str) -> subprocess.CompletedProcess: + return subprocess.run(["git", *args], cwd=repo, env=GIT_ENV, + capture_output=True, timeout=120) + + +def is_git_ignored(repo: Path, relative: str) -> bool: + """Return True when `git check-ignore` reports the path as ignored (exit 0).""" + result = git(repo, "check-ignore", "-q", "--", relative) + assert result.returncode in (0, 1), result.stderr.decode("utf-8", "replace") + return result.returncode == 0 + + +def test_gitignore_keeps_generated_env_files_out_of_a_self_update_commit(): + tmp = Path(tempfile.mkdtemp(prefix="thunder_gitignore_")) + try: + shutil.copy(REPO / ".gitignore", tmp / ".gitignore") + assert git(tmp, "init", "-q").returncode == 0 + + for relative in ("config.env", "docker.env", "deploy/prod.env"): + target = tmp / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("API_HASH=secret\n") + assert is_git_ignored(tmp, relative), \ + f"a generated {relative} must never be committed" + + (tmp / "config_sample.env").write_text('API_HASH=""\n') + assert not is_git_ignored(tmp, "config_sample.env"), \ + "the sample template must stay committable" + + (tmp / "VPS.md").write_text("ssh deploy@example.invalid\n") + assert is_git_ignored(tmp, "VPS.md"), "VPS.md carries an SSH credential" + + (tmp / "venv" / "bin").mkdir(parents=True) + (tmp / "venv" / "bin" / "python").write_text("") + assert is_git_ignored(tmp, "venv/bin/python"), \ + "README tells operators to create venv/, which must not be committed" + + (tmp / ".env").write_text("API_HASH=secret\n") + assert is_git_ignored(tmp, ".env"), "a bare .env must be ignored too" + + # Tool caches and coverage files are created by commands the docs tell + # developers to run, and none of them may be committable. + for cache in (".ruff_cache/0.0.1/index", ".pytest_cache/v/cache/lastfailed", + ".coverage"): + target = tmp / cache + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("{}\n") + assert is_git_ignored(tmp, cache), f"{cache} must not be committable" + finally: + shutil.rmtree(tmp, ignore_errors=True) diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index 0a20866f..69b69f38 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -1,9 +1,4 @@ -"""Import hygiene and configuration handling. - -These cover the three defects found by running the bot: the file_properties -import cycle, the database name derived from NAME, and /status during startup. -""" -import ast +"""Verify import hygiene, database name sanitization, and pre-startup /status handling.""" import pathlib import subprocess import sys @@ -16,8 +11,7 @@ def test_file_properties_importable_first(): - """Importing file_properties before anything else used to raise - ImportError because server/__init__ eagerly imported stream_routes.""" + """Verify file_properties is importable independently without eager server imports.""" code = "from Thunder.utils.file_properties import get_media; print('ok')" result = subprocess.run([sys.executable, "-c", code], cwd=REPO, capture_output=True, text=True, timeout=120) @@ -48,8 +42,7 @@ def test_pymongo_accepts_derived_name(self): _check_name(Var.DATABASE_NAME) def test_database_is_constructed_with_the_derived_name(self): - """Guards the regression where Database() was passed Var.NAME, which - crashes for any NAME MongoDB rejects (for example one with a space).""" + """Ensure Database uses sanitized DATABASE_NAME rather than unescaped Var.NAME.""" import inspect from Thunder.utils import database as database_module @@ -124,7 +117,85 @@ def test_update_script_parses(): assert result.returncode == 0, result.stderr +def test_install_requirements_does_not_assume_pip_exists(): + """`uv venv` creates an environment without pip. + + update.py installs dependencies with `python -m pip`, which fails there and + used to surface as a warning inside an otherwise-successful update -- so new + requirements would be missing while the update reported success. It now falls + back to `uv pip`, and warns actionably when neither is available. + """ + source = (REPO / "update.py").read_text(encoding="utf-8") + installer = source.split("def _install_requirements", 1)[1].split("\ndef ", 1)[0] + + assert "-m\", \"pip\"" in installer or "'-m', 'pip'" in installer, \ + "pip should still be tried first: it is present in the common case" + assert '"uv"' in installer and "--python" in installer, \ + "a venv created by uv venv has no pip, so uv must be tried too" + + # The fallback is useless if a failure is reported without saying what to do. + assert "--seed" in installer, \ + "the warning must tell the operator how to get a pip-bearing environment" + + +def _sandbox_skip(name): + """The real SKIP object from one of the update test files.""" + import importlib.util + + path = REPO / "tests" / f"{name}.py" + spec = importlib.util.spec_from_file_location(f"_sandbox_skip_{name}", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.SKIP + + +def test_sandbox_copies_exclude_generated_state_and_nothing_else(): + """Both update test files copy the whole project, once per test case. + + A venv lives inside the checkout (the README sets one up there) and this + project's runs to tens of thousands of files, so leaving it in the copy + patterns costs seconds per sandbox and makes the suite minutes slower for no + coverage. Caches cost less but are equally pointless. Real content must still + be copied or the tests would be running against a hollow tree. + + Asserted by calling the pattern matcher rather than reading the source: a + check on the text passes for `**/.venv`, for `.venv-backup`, and for a + comment that merely mentions the names, none of which exclude anything. + """ + names = ["Thunder", "tests", "update.py", "requirements.txt", "config.env", + ".venv", "venv", ".pytest_cache", ".ruff_cache", "logs", "__pycache__"] + for name in ("test_update_safety", "test_update_recovery"): + ignored = set(_sandbox_skip(name)(str(REPO), list(names))) + + for generated in (".venv", "venv", ".pytest_cache", ".ruff_cache"): + assert generated in ignored, ( + f"{name}: {generated}/ is copied into every sandbox" + ) + for real in ("Thunder", "tests", "update.py", "requirements.txt"): + assert real not in ignored, ( + f"{name} would exclude real content: {real}" + ) + + def test_thunder_script_resolves_python_from_its_own_directory(): script = (REPO / "thunder.sh").read_text(encoding="utf-8") assert "BASH_SOURCE" in script assert ".venv/bin/python" in script + + +def test_restart_never_execs_a_path_that_does_not_exist(): + """`/restart` replaced the process with /bin/bash unconditionally. + + On Windows that raised FileNotFoundError after telling the user the bot was + restarting, and it would do the same in an image that has no bash. The + handler must fall back to restarting the interpreter instead. + """ + source = (REPO / "Thunder" / "bot" / "plugins" / "admin.py").read_text(encoding="utf-8") + restart = source.split("async def restart_bot", 1)[1].split("\n@StreamBot", 1)[0] + + assert "os.execv" in restart, "the process is replaced, not retired" + assert '"/bin/bash"' not in restart, \ + "a hardcoded absolute path is not portable" + assert "shutil.which" in restart, "the shell must be located, not assumed" + assert "sys.executable" in restart, \ + "there must be a fallback that works without bash" diff --git a/tests/test_update_recovery.py b/tests/test_update_recovery.py new file mode 100644 index 00000000..3390262a --- /dev/null +++ b/tests/test_update_recovery.py @@ -0,0 +1,331 @@ +"""Regression tests for the update.py defects found in review.""" +import os +import shutil +import stat +import subprocess +import sys +import tempfile +from pathlib import Path + +import pytest + +REPO = Path(__file__).resolve().parent.parent + +BASE_ENV = {k: v for k, v in os.environ.items() if not k.startswith("UPSTREAM")} +BASE_ENV.update({ + "API_ID": "123456", + "API_HASH": "0" * 32, + "BOT_TOKEN": "123456:AA" + "x" * 30, + "BIN_CHANNEL": "-1001234567890", + "OWNER_ID": "1", + "DATABASE_URL": "mongodb://localhost:27017/t", +}) + +# Every test copies the project into a sandbox. Virtualenvs and tool caches are +# excluded because they are large (a .venv of this project is ~75 MB) and +# irrelevant to what is being tested; without this a suite run copies them once +# per test and takes minutes instead of seconds. +SKIP = shutil.ignore_patterns("__pycache__", "logs", "*.session*", "config.env", ".git", + ".venv", "venv", ".pytest_cache", ".ruff_cache") + + +def force_rmtree(target): + """Remove a tree that may contain read-only files. + + A real git repository keeps loose objects and pack files read-only, and + Windows refuses to delete those, so the tests need the same retry update.py + applies to itself. + """ + def on_error(func, path_, _exc): + try: + os.chmod(path_, stat.S_IWRITE) + except OSError: + pass + try: + func(path_) + except OSError: + pass + + shutil.rmtree(target, onexc=on_error) + + +def make_deployment(history: bool = True): + """A copy of the project with a real git repository and a config.env to protect. + + The repository must be genuine: update.py fetches and resets in place rather + than re-initialising one, so a stub .git directory would not exercise the + real path. Making it real also means the assertions can check the things a + user actually cares about -- branches, stash, remotes -- and not just that + some files still exist. + """ + root = Path(tempfile.mkdtemp(prefix="thunder_deploy_")) + app = root / "app" + shutil.copytree(REPO, app, ignore=SKIP) + force_rmtree(app / ".git") + (app / "config.env").write_text("KEEP_ME=1\n") + (app / "Thunder" / "logs").mkdir(parents=True, exist_ok=True) + (app / "Thunder" / "logs" / "bot.txt").write_text("live log\n") + + if history: + def git(*args): + return subprocess.run(["git", *args], cwd=app, capture_output=True, + timeout=120) + + git("init", "-q") + git("config", "user.email", "deploy@example.invalid") + git("config", "user.name", "Deploy") + git("add", "-A") + git("commit", "-qm", "deployment state") + git("branch", "-M", "main") + git("remote", "add", "origin", "https://example.invalid/deploy.git") + (app / ".git" / "CANARY").write_text("private history that must survive\n") + return root, app + + +def make_upstream(broken=False): + root = Path(tempfile.mkdtemp(prefix="thunder_ups_")) + src, bare = root / "src", root / "up.git" + shutil.copytree(REPO, src, ignore=SKIP) + (src / "UPSTREAM_MARKER.txt").write_text("from upstream\n") + if broken: + (src / "Thunder" / "broken_syntax.py").write_text("def oops(:\n pass\n") + for command in ( + ["git", "init", "-q"], + ["git", "config", "user.email", "test@example.invalid"], + ["git", "config", "user.name", "Test"], + ["git", "add", "."], + ["git", "commit", "-sm", "upstream", "-q"], + ["git", "branch", "-M", "main"], + ): + subprocess.run(command, cwd=src, capture_output=True, timeout=120) + subprocess.run(["git", "clone", "-q", "--bare", str(src), str(bare)], + cwd=root, capture_output=True, timeout=120) + return root, bare + + +def run_update(app, upstream, branch="main", timeout=400): + env = dict(BASE_ENV) + env["UPSTREAM_REPO"] = str(upstream) + env["UPSTREAM_BRANCH"] = branch + return subprocess.run([sys.executable, "update.py"], cwd=app, env=env, + capture_output=True, text=True, timeout=timeout, + encoding="utf-8", errors="replace") + + +def test_a_failed_update_restores_the_original_git_history(): + """A failed update must leave the user's git history intact.""" + upstream_root, bare = make_upstream(broken=True) + deploy_root, app = make_deployment() + try: + result = run_update(app, bare) + assert result.returncode == 1, "a broken upstream must fail" + assert (app / ".git" / "CANARY").exists(), \ + "the original .git must be intact after a rollback" + assert (app / ".git" / "refs" / "heads" / "main").exists(), \ + "branches must survive too, not just a placeholder repository" + config = (app / ".git" / "config").read_text(encoding="utf-8", errors="replace") + assert "example.invalid/deploy.git" in config, \ + "the user's own remote must be untouched" + assert "thunder@update.local" not in config, \ + "no throwaway repository may be created" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_a_successful_update_preserves_branches_stash_and_remotes(): + """The user's local git work must survive an update that succeeds. + + A rollback test cannot cover this: the damage happened when nothing failed. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + def git(*args): + return subprocess.run(["git", *args], cwd=app, capture_output=True, + text=True, timeout=120).stdout.strip() + + git("checkout", "-qb", "my-local-branch") + (app / "NOTES.md").write_text("local work\n") + git("add", "NOTES.md") + git("commit", "-qm", "local work") + (app / "stashme.txt").write_text("stash content\n") + git("add", "stashme.txt") + git("stash", "push", "-qm", "my stash") + git("checkout", "-q", "main") + + assert run_update(app, bare).returncode == 0 + + assert "my-local-branch" in git("branch"), "a local branch was lost" + assert "my stash" in git("stash", "list"), "the stash was lost" + assert "example.invalid/deploy.git" in git("remote", "-v"), "the remote was lost" + assert (app / "UPSTREAM_MARKER.txt").exists(), "the update still applied" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_a_successful_update_leaves_a_workable_checkout(): + """After a successful update the deployment must be a usable git checkout. + + The update applies upstream code and resets the working tree onto it, so the + repository has to survive that intact: still valid, still resolving to a + commit, still the user's own repository rather than a replacement. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + result = run_update(app, bare) + assert result.returncode == 0, result.stderr[-400:] + assert (app / "UPSTREAM_MARKER.txt").exists() + assert (app / "config.env").read_text().startswith("KEEP_ME") + + status = subprocess.run(["git", "status", "--porcelain"], cwd=app, + capture_output=True, timeout=120) + assert status.returncode == 0, "the remaining .git must be a valid repository" + head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=app, + capture_output=True, text=True, timeout=120) + assert head.returncode == 0 and len(head.stdout.strip()) == 40, \ + "the checkout must resolve to a commit" + + # CANARY is a stand-in for private history the original .git holds. + assert (app / ".git" / "CANARY").exists(), \ + "the update replaced the user's repository" + remotes = subprocess.run(["git", "remote", "-v"], cwd=app, capture_output=True, + text=True, timeout=120).stdout + assert "example.invalid/deploy.git" in remotes, \ + "the user's remote was replaced" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_config_recovered_when_a_previous_update_was_killed(): + """config.env must not be left stranded by a run that died mid-update. + + The backup name is fixed rather than per-process for this reason: a later run + has to be able to find the file the dead run left behind. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + (app / "config.env").unlink() + (deploy_root / ".config.env.thunder.tmp").write_text("KEEP_ME=1\n") + + result = run_update(app, bare) + + assert result.returncode == 0, result.stderr[-400:] + assert (app / "config.env").read_text().startswith("KEEP_ME"), \ + "the stranded config must be recovered, or the bot cannot start" + assert not (deploy_root / ".config.env.thunder.tmp").exists() + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_no_git_checkout_is_not_updated_even_when_git_is_installed(): + """A tarball deployment on a host that has git must be left alone. + + The check is on the checkout, not on git: without a .git directory there is + nothing to update in place, and creating one would replace the deployment. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + force_rmtree(app / ".git") + assert not (app / ".git").exists() + + result = run_update(app, bare) + + assert result.returncode == 0, "not applicable is not an error" + assert not (app / ".git").exists(), "no repository may be created here" + assert (app / "config.env").read_text().startswith("KEEP_ME") + assert not (app / "UPSTREAM_MARKER.txt").exists(), "nothing may be applied" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_rollback_keeps_the_open_log_file(): + """Thunder/logs is written to while the update runs. + + The assertion has to be that the rollback never *attempts* to remove it, not + merely that the file survives: on Windows a delete of the open file fails + silently, so a check on existence alone would pass even while the rollback + was trying to delete the whole directory. + """ + upstream_root, bare = make_upstream(broken=True) + deploy_root, app = make_deployment() + try: + result = run_update(app, bare) + assert result.returncode == 1 + + assert (app / "Thunder" / "logs" / "bot.txt").exists(), \ + "the live log directory must survive a rollback" + # The running process appends to it, so the original line is still there. + assert "live log" in (app / "Thunder" / "logs" / "bot.txt").read_text( + encoding="utf-8", errors="replace") + combined = (result.stderr or "") + (result.stdout or "") + assert "Could not clear" not in combined and "Could not remove" not in combined, \ + f"the rollback must skip the live log, not fail on it:\n{combined[-600:]}" + # ...while the code it does not own is still replaced. + assert (app / "Thunder" / "utils" / "logger.py").exists() + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_an_unusable_rollback_location_is_reported_not_crashed(): + """If the snapshot cannot be written, nothing must be changed. + + An existing checkout whose parent directory cannot hold the rollback copy: + the update has to be refused up front rather than half-applied, and it must + not crash with a traceback while the tree is mid-replacement. + """ + if os.name == "nt": + pytest.skip("making a directory unwritable is not reliable on Windows") + + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + assert (app / ".git").exists(), "this case is about a real checkout" + before = sorted(p.name for p in app.iterdir()) + # The parent directory must accept ../thunder_rollback; deny it that. + os.chmod(deploy_root, 0o500) + try: + result = run_update(app, bare) + finally: + os.chmod(deploy_root, 0o700) + + assert result.returncode == 1, "an unsafe update must be refused" + assert "Traceback" not in (result.stderr or ""), \ + "an unusable rollback location must be reported, not crash" + assert sorted(p.name for p in app.iterdir()) == before, \ + "nothing may be changed when the update cannot be made safe" + assert (app / "config.env").read_text().startswith("KEEP_ME") + assert not (app / "UPSTREAM_MARKER.txt").exists(), "nothing may be applied" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) + + +def test_a_stale_file_where_the_rollback_copy_goes_does_not_stop_the_update(): + """A stray file left by an earlier run must not be treated as a hard failure. + + _snapshot replaces whatever occupies the rollback path; only a genuinely + unwritable location is an error. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + (deploy_root / "thunder_rollback").write_text("stale file from an older run\n") + + result = run_update(app, bare) + + assert result.returncode == 0, result.stderr[-400:] + assert (app / "UPSTREAM_MARKER.txt").exists(), "the update should still apply" + assert (deploy_root / "thunder_rollback").is_dir(), \ + "the rollback copy must be a directory afterwards" + finally: + force_rmtree(deploy_root) + force_rmtree(upstream_root) diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index c4b4494c..a161f6c9 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -1,17 +1,12 @@ -"""update.py: preconditions are verified before anything destructive runs, -and a failed update restores the previous tree. - -Each test works in a throwaway copy, so the repository is never touched. -""" +"""Verify update.py preconditions and rollback in isolated project copies.""" import os import shutil +import stat import subprocess import sys import tempfile from pathlib import Path -import pytest - REPO = Path(__file__).resolve().parent.parent # update.py reads configuration at import, so give it placeholders. @@ -25,17 +20,55 @@ "DATABASE_URL": "mongodb://localhost:27017/t", }) -SKIP = shutil.ignore_patterns("__pycache__", "logs", "*.session*", "config.env", ".git") +# Generated state is excluded; see test_update_recovery.py for why. +SKIP = shutil.ignore_patterns("__pycache__", "logs", "*.session*", "config.env", ".git", + ".venv", "venv", ".pytest_cache", ".ruff_cache") + + +def force_rmtree(target): + """Remove a tree that may contain read-only files. + + A real git repository keeps its loose objects and pack files read-only, and + Windows refuses to delete those, so the tests need the same retry update.py + uses on itself. + """ + def on_error(func, path_, _exc): + try: + os.chmod(path_, stat.S_IWRITE) + except OSError: + pass + try: + func(path_) + except OSError: + pass + + shutil.rmtree(target, onexc=on_error) def make_sandbox(): - """A copy of the project with a canary .git and a config.env to protect.""" + """A copy of the project with a real git repository and a config.env to protect. + + The repository has to be genuine: update.py fetches and resets in place + rather than re-initialising, so a stub .git directory is not enough. A real + repository also makes the canary meaningful -- the history it protects is one + git can actually read. + """ target = Path(tempfile.mkdtemp(prefix="thunder_upd_")) shutil.copytree(REPO, target, dirs_exist_ok=True, ignore=SKIP) - shutil.rmtree(target / ".git", ignore_errors=True) - (target / ".git").mkdir() - (target / ".git" / "CANARY").write_text("history that must survive\n") + force_rmtree(target / ".git") (target / "config.env").write_text("KEEP_ME=1\n") + + def git(*args): + return subprocess.run(["git", *args], cwd=target, capture_output=True, + timeout=120) + + git("init", "-q") + git("config", "user.email", "deploy@example.invalid") + git("config", "user.name", "Deploy") + git("add", "-A") + git("commit", "-qm", "deployment state") + git("branch", "-M", "main") + (target / ".git" / "CANARY").write_text("history that must survive\n") return target @@ -76,7 +109,7 @@ def test_refuses_when_upstream_unset(): assert result.returncode == 0 assert (sandbox / ".git" / "CANARY").exists() finally: - shutil.rmtree(sandbox, ignore_errors=True) + force_rmtree(sandbox) def test_refuses_when_git_is_missing(): @@ -91,7 +124,27 @@ def test_refuses_when_git_is_missing(): assert result.returncode == 1 assert (sandbox / ".git" / "CANARY").exists(), "history must survive" finally: - shutil.rmtree(sandbox, ignore_errors=True) + force_rmtree(sandbox) + + +def test_no_git_and_no_checkout_is_not_an_error(): + """In container environments without git, update is skipped without error.""" + sandbox = make_sandbox() + try: + force_rmtree(sandbox / ".git") + assert not (sandbox / ".git").exists() + + env = dict(BASE_ENV) + env["UPSTREAM_REPO"] = "https://example.invalid/x.git" + env["PATH"] = "/nonexistent" + result = subprocess.run([sys.executable, "update.py"], cwd=sandbox, + env=env, capture_output=True, text=True, + timeout=180) + assert result.returncode == 0, result.stderr[-500:] + assert (sandbox / "config.env").exists(), "nothing may be touched" + assert (sandbox / "update.py").exists(), "code must be left intact" + finally: + force_rmtree(sandbox) def test_refuses_unreachable_remote(): @@ -101,7 +154,7 @@ def test_refuses_unreachable_remote(): assert result.returncode == 1 assert (sandbox / ".git" / "CANARY").exists(), "history must survive" finally: - shutil.rmtree(sandbox, ignore_errors=True) + force_rmtree(sandbox) def test_refuses_missing_branch(): @@ -112,22 +165,29 @@ def test_refuses_missing_branch(): assert result.returncode == 1 assert (sandbox / ".git" / "CANARY").exists() finally: - shutil.rmtree(sandbox, ignore_errors=True) - shutil.rmtree(root, ignore_errors=True) + force_rmtree(sandbox) + force_rmtree(root) -def test_successful_update_applies_upstream_and_keeps_config(): +def test_successful_update_applies_upstream_and_keeps_config_and_history(): root, bare = make_upstream() sandbox = make_sandbox() try: result = run_update(sandbox, upstream=str(bare)) assert result.returncode == 0, result.stderr[-500:] assert (sandbox / "UPSTREAM_MARKER.txt").exists() - assert not (sandbox / ".git" / "CANARY").exists(), "history replaced" assert (sandbox / "config.env").read_text().startswith("KEEP_ME") + + # The update applies new code without replacing the repository, so the + # user's own remote and branches are still there afterwards. + assert (sandbox / ".git" / "CANARY").exists(), \ + "a successful update must not replace the user's repository" + remotes = subprocess.run(["git", "remote", "-v"], cwd=sandbox, + capture_output=True, text=True, timeout=120) + assert "example.invalid" in remotes.stdout or "origin" in remotes.stdout finally: - shutil.rmtree(sandbox, ignore_errors=True) - shutil.rmtree(root, ignore_errors=True) + force_rmtree(sandbox) + force_rmtree(root) def test_update_is_idempotent(): @@ -138,12 +198,12 @@ def test_update_is_idempotent(): assert run_update(sandbox, upstream=str(bare)).returncode == 0 assert (sandbox / "config.env").exists() finally: - shutil.rmtree(sandbox, ignore_errors=True) - shutil.rmtree(root, ignore_errors=True) + force_rmtree(sandbox) + force_rmtree(root) def test_broken_upstream_rolls_back(): - """A tree that will not compile must not be left in place.""" + """A broken upstream that fails bytecode compilation is rolled back.""" root, bare = make_upstream(broken=True) sandbox = make_sandbox() try: @@ -154,5 +214,5 @@ def test_broken_upstream_rolls_back(): assert (sandbox / "config.env").exists() assert (sandbox / "update.py").exists(), "original code restored" finally: - shutil.rmtree(sandbox, ignore_errors=True) - shutil.rmtree(root, ignore_errors=True) + force_rmtree(sandbox) + force_rmtree(root) diff --git a/thunder.sh b/thunder.sh index 5a8b553a..cc807085 100644 --- a/thunder.sh +++ b/thunder.sh @@ -4,14 +4,25 @@ # from anywhere, and a system python3 without the dependencies only fails later. HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]:-$0}")" && pwd)" -if [ -x "$HERE/.venv/bin/python" ]; then - PYTHON="$HERE/.venv/bin/python" -elif [ -x "$HERE/venv/bin/python" ]; then - PYTHON="$HERE/venv/bin/python" -elif command -v python3 >/dev/null 2>&1; then +# A venv keeps both layouts because this script is used on Windows too, where +# the interpreter is under Scripts. python3 from PATH is the last resort: on +# Windows that name is a Store stub which exits non-zero with an install prompt, +# so the check below verifies the interpreter actually runs. +for candidate in "$HERE/.venv/bin/python" "$HERE/.venv/Scripts/python.exe" \ + "$HERE/venv/bin/python" "$HERE/venv/Scripts/python.exe"; do + if [ -x "$candidate" ]; then + PYTHON="$candidate" + break + fi +done + +if [ -z "${PYTHON:-}" ] && command -v python3 >/dev/null 2>&1 \ + && python3 -c "" >/dev/null 2>&1; then PYTHON="python3" -else - echo "No python3 interpreter found" >&2 +fi + +if [ -z "${PYTHON:-}" ]; then + echo "No working python interpreter found (looked for a venv, then python3)" >&2 exit 1 fi diff --git a/update.py b/update.py index fbd0c186..88b16344 100644 --- a/update.py +++ b/update.py @@ -1,4 +1,6 @@ -from os import chmod, environ, getpid, listdir, path, remove, rename, walk +from fnmatch import fnmatch +from os import chmod, environ, listdir, path, remove, replace, rmdir +from pathlib import PurePath from shutil import copytree, ignore_patterns, rmtree from stat import S_IWRITE from subprocess import run as srun @@ -8,17 +10,46 @@ from Thunder.utils.logger import logger +# Rollback state lives beside the tree, so replacing the tree cannot overwrite it. +_BACKUP = path.join("..", "thunder_rollback") +_CONFIG_BACKUP = path.join("..", ".config.env.thunder.tmp") + +# Regenerated or machine-specific, so never part of the code the update replaces. +# Matched against every path component, so a bare "logs" also covers the nested +# Thunder/logs, whose log file is open while this runs. +_SKIP = (".git", "config.env", "logs", "__pycache__", + "*.session", "*.session-journal", "*.session-shm", "*.session-wal") + +# A run killed between moving config.env aside and putting it back would leave the +# deployment with no configuration at all. The name is fixed rather than +# per-process precisely so that a later run can find it and recover it. +if not path.exists("config.env") and path.exists(_CONFIG_BACKUP): + try: + replace(_CONFIG_BACKUP, "config.env") + logger.warning(f"Recovered config.env from an interrupted update ({_CONFIG_BACKUP}).") + except OSError as e: + logger.error(f"Could not restore {_CONFIG_BACKUP}: {e}") + load_dotenv('config.env', override=True) UPSTREAM_REPO = environ.get("UPSTREAM_REPO", "") UPSTREAM_BRANCH = environ.get("UPSTREAM_BRANCH", "main") -_BACKUP = path.join("..", "thunder_rollback") -_SKIP = (".git", "config.env", "logs", "__pycache__", "*.session", "*.session-journal") + +def _generated(name: str) -> bool: + """True when a single path component is local state rather than deployed code.""" + return any(fnmatch(name, pattern) for pattern in _SKIP) + + +def _generated_relative(relative: str) -> bool: + """True when any part of a relative path is local state rather than code.""" + return any(_generated(part) for part in PurePath(relative).parts) def _on_rmtree_error(func, target, exc): - # git pack files are read-only on Windows; clear the bit and retry once. + # Windows refuses to delete a read-only file, and copytree preserves that bit, + # so a read-only file anywhere in the tree blocks the rollback cleanup. Clear + # the bit and retry once. try: chmod(target, S_IWRITE) except OSError: @@ -26,18 +57,38 @@ def _on_rmtree_error(func, target, exc): func(target) -def _preflight(repo: str, branch: str) -> bool: - # Nothing destructive runs until git and the remote are both proven. +def _preflight(repo: str, branch: str) -> bool | None: + """Decide whether this deployment can self-update at all. + + Returns True to proceed, None when the deployment structurally cannot update + (container image: no git and no history), False when it should be able to but + something is wrong. + """ try: probe = srun(["git", "--version"], capture_output=True) except OSError as e: + detail = str(e) + else: + detail = "" if probe.returncode == 0 else "git returned a non-zero exit code" + + has_history = path.exists(".git") + if not has_history: + # Without a checkout there is nothing to update in place, whether or not + # git happens to be installed. A tarball unpacked onto a host with git is + # the common case, and re-initialising a repository here would replace + # the deployment instead of updating it. + logger.info( + f"Self-update is not applicable in this deployment" + f"{f' ({detail})' if detail else ''}: no .git checkout to update. " + f"UPSTREAM_REPO is set but this deployment cannot update itself. " + f"Nothing has been changed.") + return None + + if detail: logger.error( - f"git is not runnable ({e}). Install git and put it on PATH " + f"git is not runnable ({detail}). Install git and put it on PATH " f"before updating; nothing has been changed.") return False - if probe.returncode != 0: - logger.error("git is not working on this host; nothing has been changed.") - return False try: check = srun( @@ -56,9 +107,35 @@ def _preflight(repo: str, branch: str) -> bool: return True +def _prune(target: str) -> None: + """Delete deployed code under `target`, leaving generated state in place. + + Recurses instead of calling rmtree on the directory as a whole, so a nested + generated path survives. Thunder/logs is the one that matters: its log file + is open while this runs, and rmtree("Thunder") would delete it. + """ + if _generated_relative(path.relpath(target)): + return + if path.isdir(target): + for entry in listdir(target): + _prune(path.join(target, entry)) + try: + rmdir(target) + except OSError: + # Not empty: something generated is still inside, which is expected. + pass + return + try: + remove(target) + except OSError as e: + logger.warning(f"Could not remove {target} during rollback: {e}") + + def _snapshot() -> None: - if path.exists(_BACKUP): + if path.isdir(_BACKUP): rmtree(_BACKUP, onexc=_on_rmtree_error) + elif path.exists(_BACKUP): + remove(_BACKUP) copytree(".", _BACKUP, ignore=ignore_patterns(*_SKIP), dirs_exist_ok=True) @@ -67,53 +144,36 @@ def _rollback() -> None: logger.error("Update failed and no rollback copy exists; code is unchanged.") return - # Clear first: the failed tree may hold files the snapshot lacks. Entries - # open in this process (the log file) are skipped rather than fatal. + # Generated state is neither deleted nor restored, so live files are left + # untouched. for entry in listdir("."): - if entry in (".git", "config.env", "logs", _BACKUP.split(path.sep)[-1]): + if _generated(entry): continue - target = path.join(".", entry) - try: - if path.isdir(target): - rmtree(target, onexc=_on_rmtree_error) - else: - remove(target) - except OSError as e: - logger.warning(f"Could not clear {target} during rollback: {e}") + _prune(path.join(".", entry)) copytree(_BACKUP, ".", dirs_exist_ok=True) - # A directory that could not be cleared still holds whatever the failed - # update added; delete anything the snapshot does not contain. - for root, _dirs, files in walk(".", topdown=False): - if root.startswith("." + path.sep + ".git") or root == "." + path.sep + "logs": - continue - for name in files: - candidate = path.join(root, name) - if not path.exists(path.join(_BACKUP, candidate)): - try: - remove(candidate) - except OSError: - pass - logger.error("Update failed; rolled back to the previous working code.") def _apply_upstream(repo: str, branch: str) -> bool: - if path.exists(".git"): - rmtree(".git", onexc=_on_rmtree_error) - - # Argument lists, never a shell (no injection); git config is local, not --global. - for cmd in ( - ["git", "init", "-q"], - ["git", "config", "user.email", "thunder@update.local"], - ["git", "config", "user.name", "Thunder"], - ["git", "add", "."], - ["git", "commit", "-sm", "update", "-q"], - ["git", "remote", "add", "origin", repo], - ["git", "fetch", "origin", "-q"], - ["git", "reset", "--hard", f"origin/{branch}", "-q"], - ): + """Fetch and reset onto the upstream branch, in the user's own repository. + + Deliberately never re-initialises the repository. Doing so replaces it, which + costs the user their branches, stashes and remotes. Only the working tree + changes here, and it is snapshotted for rollback before this runs. + """ + # Argument lists, never a shell (no injection). Anything the user configured + # stays configured: only the remote we need is added if it is missing. + remotes = srun(["git", "remote"], capture_output=True) + known = (remotes.stdout or b"").decode("utf-8", "replace").split() + + commands = [["git", "fetch", "--prune", "--quiet", repo, branch]] + if "origin" not in known: + commands.append(["git", "remote", "add", "origin", repo]) + commands.append(["git", "reset", "--hard", "--quiet", "FETCH_HEAD"]) + + for cmd in commands: try: result = srun(cmd) except OSError as e: @@ -122,6 +182,7 @@ def _apply_upstream(repo: str, branch: str) -> bool: if result.returncode != 0: logger.error(f"git {cmd[1] if len(cmd) > 1 else ''} failed.") return False + return True @@ -129,19 +190,32 @@ def _install_requirements() -> bool: # A package that will not build here is reported, never a rollback. if not path.exists("requirements.txt"): return True - try: - result = srun( - [executable, "-m", "pip", "install", "-q", "-r", "requirements.txt"], - capture_output=True, - ) - except OSError as e: - logger.warning(f"Could not run pip: {e}") - return True - if result.returncode != 0: + + # pip is not guaranteed: `uv venv` creates an environment without it, and a + # deployment set up that way would otherwise fail here on every update while + # still reporting success. Try pip, then uv, and say plainly when neither is + # available rather than continuing silently. + attempts = ( + [executable, "-m", "pip", "install", "-q", "-r", "requirements.txt"], + ["uv", "pip", "install", "--python", executable, "-q", "-r", "requirements.txt"], + ) + last_error = "" + for command in attempts: + try: + result = srun(command, capture_output=True) + except OSError as e: + last_error = f"could not run {command[0]}: {e}" + continue + if result.returncode == 0: + return True tail = (result.stderr or b"").decode("utf-8", "replace").strip().splitlines() - logger.warning( - f"Dependencies could not be fully installed " - f"({tail[-1] if tail else 'unknown error'}); continuing.") + last_error = tail[-1] if tail else f"{command[0]} exited {result.returncode}" + + logger.warning( + f"Dependencies could not be fully installed ({last_error}); continuing. " + f"New requirements may be missing, in which case the bot will fail to " + f"start: install them yourself, or recreate the environment with " + f"`uv venv --seed` so it contains pip.") return True @@ -157,21 +231,29 @@ def _validate() -> bool: return result.returncode == 0 -def _run_update(repo: str, branch: str) -> bool: - if not _preflight(repo, branch): - return False +def _run_update(repo: str, branch: str) -> bool | None: + preflight = _preflight(repo, branch) + if preflight is not True: + # False: preconditions failed. None: self-update does not apply here. + return preflight - _snapshot() + try: + _snapshot() + except OSError as e: + # Nothing has been changed yet, so report rather than risk a half state. + logger.error( + f"Could not create a rollback copy in {path.dirname(_BACKUP)} ({e}). " + f"That directory must be writable for an update to be safe. " + f"Nothing has been changed.") + return False - # config.env is normally gitignored, but keep it safe either way. - # Move config aside for the reset. The backup lives beside the tree and is - # removed on the way out, so a stale one from a killed run cannot block - # the next update. - config_backup = path.join("..", f".config.env.{getpid()}.tmp") - if path.exists(config_backup): - remove(config_backup) + # Move config aside: the reset below replaces tracked files, and config.env + # is untracked in a user's checkout. The name is fixed, not per-process, so a + # leftover from a killed run can be recovered by the next import. + if path.exists(_CONFIG_BACKUP): + remove(_CONFIG_BACKUP) if path.exists("config.env"): - rename("config.env", config_backup) + replace("config.env", _CONFIG_BACKUP) try: ok = _apply_upstream(repo, branch) @@ -182,18 +264,23 @@ def _run_update(repo: str, branch: str) -> bool: if not ok: _rollback() return False + logger.info("Successfully updated with Latest Updates!") return True finally: - if path.exists(config_backup): - rename(config_backup, "config.env") + # replace, not rename: on Windows rename raises FileExistsError if the + # destination was recreated during the update, which would escape the + # finally block as a crash. + if path.exists(_CONFIG_BACKUP): + replace(_CONFIG_BACKUP, "config.env") def main() -> int: if not UPSTREAM_REPO: logger.info("No UPSTREAM_REPO set, skipping update") return 0 - return 0 if _run_update(UPSTREAM_REPO, UPSTREAM_BRANCH) else 1 + result = _run_update(UPSTREAM_REPO, UPSTREAM_BRANCH) + return 0 if result in (True, None) else 1 if __name__ == "__main__":