From bb1668ce3ce29de632e948e3c3bc2044f09ddebc Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 12:45:22 +0530 Subject: [PATCH 1/5] fix: await the dedup cursor, and drop the C toolchain Duplicate-user recovery raised TypeError exactly when it ran: pymongo's aggregate is async and the cursor was iterated directly. Two tests cover it, both failing before the fix. tgcrypto has no wheel past cp311, so every install needed a compiler. tgcrypto-pyrofork ships cp313/cp314 wheels. uvloop's pin predated its own. Cleared five lint findings and the dead requested_action parameter. --- AGENTS.md | 6 +-- README.md | 2 +- Thunder/__main__.py | 2 +- Thunder/bot/plugins/admin.py | 1 - Thunder/server/stream_routes.py | 5 +- Thunder/template/dl.html | 27 ---------- Thunder/utils/broadcast.py | 2 - Thunder/utils/database.py | 2 +- Thunder/utils/messages.py | 1 - Thunder/utils/render_template.py | 25 ++++----- requirements.txt | 7 ++- tests/test_database_dedup.py | 91 ++++++++++++++++++++++++++++++++ tests/test_render_template.py | 22 ++++++++ tests/test_runtime_safety.py | 1 - tests/test_update_safety.py | 2 - 15 files changed, 135 insertions(+), 61 deletions(-) delete mode 100644 Thunder/template/dl.html create mode 100644 tests/test_database_dedup.py create mode 100644 tests/test_render_template.py diff --git a/AGENTS.md b/AGENTS.md index 57b94d21..942c2283 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,8 +14,8 @@ python3 update.py # Update only (rolls back if the new tree is unusable ```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 @@ -38,7 +38,7 @@ 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) ``` ## Key Imports diff --git a/README.md b/README.md index a609787d..2bb8263e 100644 --- a/README.md +++ b/README.md @@ -572,7 +572,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/__main__.py b/Thunder/__main__.py index df6786bf..146c4619 100644 --- a/Thunder/__main__.py +++ b/Thunder/__main__.py @@ -318,7 +318,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/plugins/admin.py b/Thunder/bot/plugins/admin.py index 82d0e729..23658982 100644 --- a/Thunder/bot/plugins/admin.py +++ b/Thunder/bot/plugins/admin.py @@ -4,7 +4,6 @@ import html import os import shutil -import sys import time from io import BytesIO diff --git a/Thunder/server/stream_routes.py b/Thunder/server/stream_routes.py index 9ce7ed9c..f09c7b1d 100644 --- a/Thunder/server/stream_routes.py +++ b/Thunder/server/stream_routes.py @@ -318,7 +318,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 +347,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/broadcast.py b/Thunder/utils/broadcast.py index 044dcd42..23c39e69 100644 --- a/Thunder/utils/broadcast.py +++ b/Thunder/utils/broadcast.py @@ -99,12 +99,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/database.py b/Thunder/utils/database.py index 6395a1b9..9acdbde1 100644 --- a/Thunder/utils/database.py +++ b/Thunder/utils/database.py @@ -31,7 +31,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/messages.py b/Thunder/utils/messages.py index feb8f040..d7b6bc9e 100644 --- a/Thunder/utils/messages.py +++ b/Thunder/utils/messages.py @@ -42,7 +42,6 @@ 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 = ( diff --git a/Thunder/utils/render_template.py b/Thunder/utils/render_template.py index 5c6ef1a1..882bb82f 100644 --- a/Thunder/utils/render_template.py +++ b/Thunder/utils/render_template.py @@ -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/requirements.txt b/requirements.txt index fdba46f3..1f5792ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,8 +7,11 @@ pymongo psutil python-dotenv speedtest-cli -tgcrypto +# tgcrypto-pyrofork, not tgcrypto: the original project last released in 2022 +# with wheels only up to cp311, so on 3.13 it compiles from source and needs a +# C toolchain. This fork ships cp313/cp314 wheels and imports as "tgcrypto". +tgcrypto-pyrofork # 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" +uvloop>=0.22.1; sys_platform != "win32" and sys_platform != "cygwin" diff --git a/tests/test_database_dedup.py b/tests/test_database_dedup.py new file mode 100644 index 00000000..29bfa524 --- /dev/null +++ b/tests/test_database_dedup.py @@ -0,0 +1,91 @@ +"""The duplicate-user recovery path must await the aggregate cursor. + +pymongo's ``AsyncCollection.aggregate`` is ``async def``, so the call returns a +coroutine, not a cursor, and ``async for`` over it raises +``TypeError: 'async for' requires an object with __aiter__ method, got coroutine``. + +That code runs only when ``create_index("id", unique=True)`` raises +DuplicateKeyError, so nothing else in the suite reaches it. +""" +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(): + """The real caller: this is the only path that reaches the dedup.""" + 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_render_template.py b/tests/test_render_template.py new file mode 100644 index 00000000..5ccd7b5d --- /dev/null +++ b/tests/test_render_template.py @@ -0,0 +1,22 @@ +"""render_media_page drives req.html: the player page must carry the file name +and the source URL with ``disposition=inline``. +""" +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): + """The loader is CWD-relative; point it at the repo's template directory so + the test does not depend on where pytest was started from.""" + 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_runtime_safety.py b/tests/test_runtime_safety.py index 0a20866f..a07a51bd 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -3,7 +3,6 @@ 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 import pathlib import subprocess import sys diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index c4b4494c..359e5790 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -10,8 +10,6 @@ import tempfile from pathlib import Path -import pytest - REPO = Path(__file__).resolve().parent.parent # update.py reads configuration at import, so give it placeholders. From 56a3038471d24ae088e74a3ff666d5c4eabdf677 Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 12:45:22 +0530 Subject: [PATCH 2/5] build: unprivileged image, and no secrets in the build context Root, gcc, git and libssl-dev existed for one package. Every dependency has a wheel now, so the image drops from 977 MB to 287 MB and runs as uid 10001. COPY . . was baking config.env and a 115 MB .venv into images built from a deployment tree. The new .dockerignore excludes them, with a test: a pattern that looks right and silently misses the file is worse than no pattern. update.py reports a deployment that cannot self-update as not applicable rather than an error, so a container without git boots clean. --- .dockerignore | 36 ++++++++++++++ .gitignore | 8 +++- AGENTS.md | 18 ++++++- Dockerfile | 22 ++++----- README.md | 39 ++++++++++++++-- Thunder/__init__.py | 1 - Thunder/__main__.py | 6 ++- Thunder/bot/__init__.py | 2 +- Thunder/bot/clients.py | 6 ++- Thunder/bot/plugins/admin.py | 6 ++- Thunder/bot/plugins/callbacks.py | 6 ++- Thunder/bot/plugins/common.py | 2 +- Thunder/bot/plugins/stream.py | 6 ++- Thunder/server/__init__.py | 1 - Thunder/server/exceptions.py | 1 - Thunder/server/stream_routes.py | 6 ++- Thunder/utils/bot_utils.py | 6 ++- Thunder/utils/broadcast.py | 6 ++- Thunder/utils/canonical_files.py | 7 +++ Thunder/utils/commands.py | 2 + Thunder/utils/config_parser.py | 2 +- Thunder/utils/custom_dl.py | 6 ++- Thunder/utils/database.py | 6 ++- Thunder/utils/decorators.py | 6 ++- Thunder/utils/file_properties.py | 7 ++- Thunder/utils/force_channel.py | 5 +- Thunder/utils/human_readable.py | 2 +- Thunder/utils/keepalive.py | 2 +- Thunder/utils/logger.py | 5 +- Thunder/utils/messages.py | 80 +++++++++++++------------------- Thunder/utils/rate_limiter.py | 6 ++- Thunder/utils/render_template.py | 2 +- Thunder/utils/shortener.py | 6 ++- Thunder/utils/speedtest.py | 2 +- Thunder/utils/time_format.py | 2 +- Thunder/utils/tokens.py | 6 ++- Thunder/vars.py | 6 ++- requirements.txt | 8 +--- tests/test_database_dedup.py | 12 +---- tests/test_render_template.py | 7 +-- tests/test_repo_hygiene.py | 54 +++++++++++++++++++++ tests/test_runtime_safety.py | 12 ++--- tests/test_update_safety.py | 28 ++++++++--- update.py | 50 ++++++++++++-------- 44 files changed, 355 insertions(+), 154 deletions(-) create mode 100644 .dockerignore create mode 100644 tests/test_repo_hygiene.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..a3e43986 --- /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 +pytest.ini +.github +.gitignore +.python-version +Dockerfile +.dockerignore +README.md +AGENTS.md +VPS.md +PLAN.md + diff --git a/.gitignore b/.gitignore index a9dc32e4..e4732e54 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,14 @@ *$py.class *.so .venv/ +venv/ .Python -config.env +# Exclude env files (update.py runs `git add .` on self-update); track only the template. +*.env +!config_sample.env +# Local operational files containing credentials or scratch notes. +VPS.md +PLAN.md log.text .vscode/ **/__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index 942c2283..b9582de1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ 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 @@ -41,6 +42,19 @@ Thunder/ └── 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` (`chown 10001:10001` or `644`; + a root-only `600` fails). +- 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`. + ## Key Imports ```python @@ -82,8 +96,8 @@ python -m pytest -q # ~60s; no network or Telegram credentials needed ``` 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, and .gitignore hygiene. ## Debugging diff --git a/Dockerfile b/Dockerfile index 63d8ea78..65cc843c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,21 +5,17 @@ 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. +# Update from UPSTREAM_REPO if set, then start (update failure does not block startup). CMD ["bash", "thunder.sh"] diff --git a/README.md b/README.md index 2bb8263e..ecfda4ca 100644 --- a/README.md +++ b/README.md @@ -307,13 +307,44 @@ 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 +sudo chown 10001:10001 config.env +docker run -d --name thunder -p 8080:8080 \ + -v "$PWD/config.env:/app/config.env:ro" thunder ``` +Note the `chown`: the container runs as uid `10001`, so it must be able to read +`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 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 146c4619..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 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 23658982..34ee65ae 100644 --- a/Thunder/bot/plugins/admin.py +++ b/Thunder/bot/plugins/admin.py @@ -1,4 +1,8 @@ -# 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)``, so the +file is the bot's administrative surface. +""" import asyncio import html 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 f09c7b1d..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 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 23c39e69..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 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..5cc7e1ab 100644 --- a/Thunder/utils/config_parser.py +++ b/Thunder/utils/config_parser.py @@ -1,4 +1,4 @@ -# Thunder/utils/config_parser.py +"""Collects MULTI_TOKEN1..N from the environment into client slots.""" import os from typing import Dict, Optional 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 9acdbde1..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 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 d7b6bc9e..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,7 +39,7 @@ 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." @@ -50,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.**" @@ -71,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 = ( @@ -93,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" @@ -107,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!**" @@ -117,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" @@ -133,9 +131,7 @@ MSG_BUTTON_CLOSE = "✖ Close" -# ===================================================================================== -# ====== COMMAND RESPONSES (User-facing) ====== -# ===================================================================================== +# COMMAND RESPONSES (User-facing) MSG_WELCOME = ( "🌟 **Welcome, {user_name}!** 🌟\n\n" @@ -196,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" @@ -204,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" @@ -222,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" @@ -233,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" @@ -244,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 = ( @@ -258,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 = ( @@ -288,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" @@ -321,9 +307,7 @@ ) -# ===================================================================================== -# ====== FILE TYPE DESCRIPTIONS ====== -# ===================================================================================== +# FILE TYPE DESCRIPTIONS MSG_FILE_TYPE_DOCUMENT = "📄 Document" MSG_FILE_TYPE_PHOTO = "🖼️ Photo" MSG_FILE_TYPE_VIDEO = "🎬 Video" @@ -334,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" @@ -348,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 882bb82f..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 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/requirements.txt b/requirements.txt index 1f5792ba..08b84617 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,11 +7,7 @@ pymongo psutil python-dotenv speedtest-cli -# tgcrypto-pyrofork, not tgcrypto: the original project last released in 2022 -# with wheels only up to cp311, so on 3.13 it compiles from source and needs a -# C toolchain. This fork ships cp313/cp314 wheels and imports as "tgcrypto". +# Fork provides cp313/cp314 wheels (avoids C toolchain at build time) and imports as "tgcrypto". tgcrypto-pyrofork -# 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 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_database_dedup.py b/tests/test_database_dedup.py index 29bfa524..b20002e9 100644 --- a/tests/test_database_dedup.py +++ b/tests/test_database_dedup.py @@ -1,12 +1,4 @@ -"""The duplicate-user recovery path must await the aggregate cursor. - -pymongo's ``AsyncCollection.aggregate`` is ``async def``, so the call returns a -coroutine, not a cursor, and ``async for`` over it raises -``TypeError: 'async for' requires an object with __aiter__ method, got coroutine``. - -That code runs only when ``create_index("id", unique=True)`` raises -DuplicateKeyError, so nothing else in the suite reaches it. -""" +"""Verify _deduplicate_users awaits AsyncCollection.aggregate coroutine on DuplicateKeyError.""" from pymongo.errors import DuplicateKeyError from Thunder.utils.database import Database @@ -83,7 +75,7 @@ async def test_deduplicate_users_awaits_the_aggregate_cursor(): async def test_ensure_indexes_recovers_from_duplicate_keys(): - """The real caller: this is the only path that reaches the dedup.""" + """Verify ensure_indexes recovers from DuplicateKeyError by running deduplication.""" col = RecoveryCollection(keep_ids=[10, 20]) db = make_db(col) diff --git a/tests/test_render_template.py b/tests/test_render_template.py index 5ccd7b5d..f422a31a 100644 --- a/tests/test_render_template.py +++ b/tests/test_render_template.py @@ -1,6 +1,4 @@ -"""render_media_page drives req.html: the player page must carry the file name -and the source URL with ``disposition=inline``. -""" +"""Verify render_media_page embeds filename and inline disposition source URL.""" from pathlib import Path from jinja2 import FileSystemLoader @@ -11,8 +9,7 @@ async def test_render_media_page_returns_player_with_inline_source(monkeypatch): - """The loader is CWD-relative; point it at the repo's template directory so - the test does not depend on where pytest was started from.""" + """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" diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.py new file mode 100644 index 00000000..111d46aa --- /dev/null +++ b/tests/test_repo_hygiene.py @@ -0,0 +1,54 @@ +"""Verify .gitignore prevents credential leaks during self-update (`update.py` runs `git add .`).""" +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" + finally: + shutil.rmtree(tmp, ignore_errors=True) diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index a07a51bd..fbb14208 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -1,8 +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. -""" +"""Verify import hygiene, database name sanitization, and pre-startup /status handling.""" import pathlib import subprocess import sys @@ -15,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) @@ -47,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 diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index 359e5790..312e8f65 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -1,8 +1,4 @@ -"""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 subprocess @@ -92,6 +88,26 @@ def test_refuses_when_git_is_missing(): shutil.rmtree(sandbox, ignore_errors=True) +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: + shutil.rmtree(sandbox / ".git", ignore_errors=True) + 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: + shutil.rmtree(sandbox, ignore_errors=True) + + def test_refuses_unreachable_remote(): sandbox = make_sandbox() try: @@ -141,7 +157,7 @@ def test_update_is_idempotent(): 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: diff --git a/update.py b/update.py index fbd0c186..b47d7a9e 100644 --- a/update.py +++ b/update.py @@ -14,7 +14,9 @@ UPSTREAM_BRANCH = environ.get("UPSTREAM_BRANCH", "main") _BACKUP = path.join("..", "thunder_rollback") -_SKIP = (".git", "config.env", "logs", "__pycache__", "*.session", "*.session-journal") +# Exclude regenerated and machine-specific files (sessions, logs, caches) from rollback. +_SKIP = (".git", "config.env", "logs", "__pycache__", + "*.session", "*.session-journal", "*.session-shm", "*.session-wal") def _on_rmtree_error(func, target, exc): @@ -26,18 +28,30 @@ 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: + # Returns None when self-update cannot apply (e.g. no git in container), False on error. try: probe = srun(["git", "--version"], capture_output=True) except OSError as e: + detail = str(e) + else: + if probe.returncode == 0: + detail = "" + else: + detail = "git returned a non-zero exit code" + + if detail: + if not path.exists(".git"): + # Container image: no git and no history is normal, not a failure. + logger.info( + f"Self-update is not applicable in this deployment ({detail}); " + f"UPSTREAM_REPO is set but this deployment cannot update itself. " + f"Nothing has been changed.") + return None 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( @@ -67,8 +81,7 @@ 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. + # Remove files absent from snapshot; skip open files (e.g. active log). for entry in listdir("."): if entry in (".git", "config.env", "logs", _BACKUP.split(path.sep)[-1]): continue @@ -83,8 +96,7 @@ def _rollback() -> None: 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. + # Delete new files inside directories that could not be removed directly. for root, _dirs, files in walk(".", topdown=False): if root.startswith("." + path.sep + ".git") or root == "." + path.sep + "logs": continue @@ -157,16 +169,15 @@ 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() - # 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. + # Move config aside for the git reset; a stale backup from a killed run is removed first. config_backup = path.join("..", f".config.env.{getpid()}.tmp") if path.exists(config_backup): remove(config_backup) @@ -193,7 +204,8 @@ 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__": From 7ba93bb4417d1c8f56b6c26b6f74189d9c9d10ff Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 12:45:23 +0530 Subject: [PATCH 3/5] ci: gate the image on the tests, and test it before publishing dockerize.yml pushed thunder:latest on every push to main with no dependency on the test job, so a red main shipped an image. One workflow now: the image is built, smoke-tested, then published. Fork PRs never see the Docker Hub secret. Suite runs on Linux and Windows at 3.13 plus 3.14, and weekly against fresh dependencies, since requirements.txt floats on purpose. Actions pinned to SHAs. pytest.ini becomes pyproject.toml. New tests cover plugin handler registration, the platform-only deployment files, and the workflow's own invariants. Also fixed /restart, which exec'd a hardcoded /bin/bash and crashed on Windows, and four ways update.py could lose a user's work or their config.env. --- .dockerignore | 2 +- .github/dependabot.yml | 8 + .github/workflows/dockerize.yml | 26 --- .github/workflows/tests.yml | 104 ++++++++++- .gitignore | 1 + AGENTS.md | 23 ++- Dockerfile | 3 +- README.md | 31 ++- Thunder/bot/plugins/admin.py | 13 +- pyproject.toml | 20 ++ pytest.ini | 7 - requirements-dev.txt | 4 + tests/test_ci_workflow.py | 233 +++++++++++++++++++++++ tests/test_deployment_entrypoints.py | 25 +++ tests/test_plugin_registration.py | 137 ++++++++++++++ tests/test_repo_hygiene.py | 8 + tests/test_runtime_safety.py | 18 ++ tests/test_update_recovery.py | 269 +++++++++++++++++++++++++++ update.py | 182 +++++++++++++----- 19 files changed, 1001 insertions(+), 113 deletions(-) create mode 100644 .github/dependabot.yml delete mode 100644 .github/workflows/dockerize.yml create mode 100644 pyproject.toml delete mode 100644 pytest.ini create mode 100644 tests/test_ci_workflow.py create mode 100644 tests/test_deployment_entrypoints.py create mode 100644 tests/test_plugin_registration.py create mode 100644 tests/test_update_recovery.py diff --git a/.dockerignore b/.dockerignore index a3e43986..04e2478b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -23,7 +23,7 @@ __pycache__ .coverage.json tests requirements-dev.txt -pytest.ini +pyproject.toml .github .gitignore .python-version 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..c90d36a9 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,26 +1,112 @@ -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: . + # Public and private repositories default differently, so it is set + # explicitly. + provenance: mode=max + # The smoke test runs the image below. With the container driver that + # build-push-action uses, the result stays in the build cache unless it + # is loaded, so without this `docker run` would find nothing. On a push + # the image is in the registry instead, so loading is unnecessary. + load: ${{ github.event_name != 'push' }} + push: ${{ github.event_name == 'push' }} + tags: fyaz05/thunder:latest + - 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. + # 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 configuration. + env: + # A pull request has the image loaded locally; a push has it in the + # registry, addressed by the digest the build step just produced. + IMAGE: ${{ github.event_name == 'push' && format('fyaz05/thunder@{0}', steps.build.outputs.digest) || 'fyaz05/thunder:latest' }} + 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 \ + "$IMAGE" python -c \ + "import Thunder, Thunder.__main__, uvloop, tgcrypto, aiohttp; print('ok', Thunder.__version__)" diff --git a/.gitignore b/.gitignore index e4732e54..35658e24 100644 --- a/.gitignore +++ b/.gitignore @@ -34,5 +34,6 @@ wheels/ .installed.cfg *.egg .pytest_cache/ +.ruff_cache/ __pycache__/ *.pyc diff --git a/AGENTS.md b/AGENTS.md index b9582de1..f4cff7ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,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 @@ -49,12 +49,16 @@ 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` (`chown 10001:10001` or `644`; - a root-only `600` fails). +- 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 @@ -91,16 +95,19 @@ 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; no network or Telegram 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, -update.py preconditions and rollback, and .gitignore hygiene. +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`. ## 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 65cc843c..102291b2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,5 +17,6 @@ USER 10001:10001 EXPOSE 8080 -# Update from UPSTREAM_REPO if set, then start (update failure does not block 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 ecfda4ca..28794815 100644 --- a/README.md +++ b/README.md @@ -309,13 +309,19 @@ nano config.env # Edit your settings # 3. Build and run (the config is mounted — it is not baked into the image) docker build -t thunder . -sudo chown 10001:10001 config.env docker run -d --name thunder -p 8080:8080 \ -v "$PWD/config.env:/app/config.env:ro" thunder ``` -Note the `chown`: the container runs as uid `10001`, so it must be able to read -`config.env`. `--stop-timeout 30` is optional — it lets the server's 25s shutdown drain +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 @@ -419,10 +425,10 @@ 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`. @@ -590,9 +596,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 diff --git a/Thunder/bot/plugins/admin.py b/Thunder/bot/plugins/admin.py index 34ee65ae..e5743f9c 100644 --- a/Thunder/bot/plugins/admin.py +++ b/Thunder/bot/plugins/admin.py @@ -1,13 +1,13 @@ """Owner commands: users, broadcast, status, stats, restart, logs, shell. -Every handler here is registered with ``filters.user(Var.OWNER_ID)``, so the -file is the bot's administrative surface. +Every handler here is registered with ``filters.user(Var.OWNER_ID)``. """ import asyncio import html import os import shutil +import sys import time from io import BytesIO @@ -181,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/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/tests/test_ci_workflow.py b/tests/test_ci_workflow.py new file mode 100644 index 00000000..039e7ae4 --- /dev/null +++ b/tests/test_ci_workflow.py @@ -0,0 +1,233 @@ +"""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: + assert PUSH_EVENT in str(step["with"]["push"]), "only a push event may publish" + + +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 smoke test can only run an image that is somewhere: loaded into the + # local daemon, or pushed to the registry. Pushing covers only the events it + # is true for, so a conditional push needs a load for the other events -- + # without it the container-driver build leaves nothing to run. + push = str(with_.get("push", "")) + load = str(with_.get("load", "")) + pushing_is_conditional = "github.event_name" in push + + assert push in ("true", "false") or pushing_is_conditional, f"unexpected push value: {push!r}" + if with_.get("push") in (None, "false", False) or pushing_is_conditional: + assert "load" in with_, "no push and no load: the smoke test would find no image" + assert load.strip() == "true" or "!= 'push'" in load, ( + f"load must cover the non-push events, got {load!r}" + ) + + # 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_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_repo_hygiene.py b/tests/test_repo_hygiene.py index 111d46aa..879a4be4 100644 --- a/tests/test_repo_hygiene.py +++ b/tests/test_repo_hygiene.py @@ -50,5 +50,13 @@ def test_gitignore_keeps_generated_env_files_out_of_a_self_update_commit(): (tmp / ".env").write_text("API_HASH=secret\n") assert is_git_ignored(tmp, ".env"), "a bare .env must be ignored too" + + # Tool caches are created by commands AGENTS.md tells developers to run, + # and update.py runs `git add .`, so neither may be committable. + for cache in (".ruff_cache/0.0.1/index", ".pytest_cache/v/cache/lastfailed"): + target = tmp / cache + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("{}\n") + assert is_git_ignored(tmp, cache), f"{cache} is a regenerable tool cache" finally: shutil.rmtree(tmp, ignore_errors=True) diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index fbb14208..d26b4ee8 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -121,3 +121,21 @@ 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..4e69a636 --- /dev/null +++ b/tests/test_update_recovery.py @@ -0,0 +1,269 @@ +"""Regression tests for the update.py defects found in review. + +Two of the defects covered here destroy data; the test that guards new +behaviour rather than a defect says so in its own docstring. +""" +import os +import shutil +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", +}) + +SKIP = shutil.ignore_patterns("__pycache__", "logs", "*.session*", "config.env", ".git") + + +def make_deployment(history: bool = True): + """A checkout-shaped copy with private history and a config.env to protect. + + The .git directory is a realistic stub: a rollback test needs to prove the + real thing came back, so it has the files a real repository would have. + """ + root = Path(tempfile.mkdtemp(prefix="thunder_deploy_")) + app = root / "app" + shutil.copytree(REPO, app, ignore=SKIP) + shutil.rmtree(app / ".git", ignore_errors=True) + if history: + git = app / ".git" + (git / "refs" / "heads").mkdir(parents=True) + (git / "HEAD").write_text("ref: refs/heads/main\n") + (git / "config").write_text( + '[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n' + '\turl = https://example.invalid/private.git\n') + (git / "refs" / "heads" / "main").write_text("0" * 40 + "\n") + (git / "CANARY").write_text("private history that must survive\n") + (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") + 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(): + """The tree must never come back without the history it had before. + + _apply_upstream re-initialises the repository to fetch upstream, so a failure + afterwards used to leave the user with a throwaway one-commit repo and their + branches, remotes and stashes gone. + """ + 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 back 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/private.git" in config, \ + "the original remotes must be intact" + assert "thunder@update.local" not in config, \ + "a rollback must not leave the throwaway repository in place" + finally: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +def test_a_successful_update_leaves_a_workable_checkout(): + """After a successful update the deployment must be a usable git checkout. + + This one is not a regression test for a pre-existing defect: the pre-fix code + never preserved history, so it had no backup to leak. It guards the new + behaviour -- that the preserved history is cleaned up and the repository left + behind still works -- which nothing else covers. + """ + 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") + assert not (deploy_root / "thunder_git_backup").exists(), \ + "the preserved history is obsolete once the update succeeded" + + 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 + finally: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +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: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +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. + + Previously the missing-.git check only ran when git itself was unusable, so + an unpacked archive was re-initialised as a git repository. + """ + upstream_root, bare = make_upstream() + deploy_root, app = make_deployment() + try: + shutil.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: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +def test_rollback_keeps_the_open_log_file(): + """Thunder/logs is written to while the update runs. + + The rollback used to exempt a top-level "logs" directory, which never exists + (the real path is Thunder/logs), so the whole Thunder/ tree was deleted. On + Windows the deletion silently failed with WinError 32 and only the log file's + in-use status saved it; on Linux it was removed. The assertion therefore has + to be that the rollback never tries to remove it, which holds on both. + """ + 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: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +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: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) + + +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: + shutil.rmtree(deploy_root, ignore_errors=True) + shutil.rmtree(upstream_root, ignore_errors=True) diff --git a/update.py b/update.py index b47d7a9e..8fe24c8e 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, rename, rmdir +from pathlib import PurePath from shutil import copytree, ignore_patterns, rmtree from stat import S_IWRITE from subprocess import run as srun @@ -8,15 +10,40 @@ from Thunder.utils.logger import logger +# Rollback state lives beside the tree, so replacing the tree cannot overwrite it. +_BACKUP = path.join("..", "thunder_rollback") +_GIT_BACKUP = path.join("..", "thunder_git_backup") +_CONFIG_BACKUP = path.join("..", ".config.env.thunder.tmp") + +# Regenerated or machine-specific, so never part of the code the update replaces. +# "logs" is a directory name: it also covers the live log directory, Thunder/logs, +# whose 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: + rename(_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") -# Exclude regenerated and machine-specific files (sessions, logs, caches) from rollback. -_SKIP = (".git", "config.env", "logs", "__pycache__", - "*.session", "*.session-journal", "*.session-shm", "*.session-wal") + +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: + return any(_generated(part) for part in PurePath(relative).parts) def _on_rmtree_error(func, target, exc): @@ -29,25 +56,33 @@ def _on_rmtree_error(func, target, exc): def _preflight(repo: str, branch: str) -> bool | None: - # Returns None when self-update cannot apply (e.g. no git in container), False on error. + """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: - if probe.returncode == 0: - detail = "" - else: - detail = "git returned a non-zero exit code" + 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: - if not path.exists(".git"): - # Container image: no git and no history is normal, not a failure. - logger.info( - f"Self-update is not applicable in this deployment ({detail}); " - f"UPSTREAM_REPO is set but this deployment cannot update itself. " - f"Nothing has been changed.") - return None logger.error( f"git is not runnable ({detail}). Install git and put it on PATH " f"before updating; nothing has been changed.") @@ -70,9 +105,49 @@ def _preflight(repo: str, branch: str) -> bool | None: 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 _restore_git() -> None: + """Put the original repository back, discarding the one git init created. + + Only ever called from a failed update. If there is no backup the deployment + had no history to begin with, so what is in .git now is disposable. + """ + if not path.exists(_GIT_BACKUP): + return + if path.exists(".git"): + rmtree(".git", onexc=_on_rmtree_error) + rename(_GIT_BACKUP, ".git") + logger.info("Original git history restored.") + + 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) @@ -81,39 +156,28 @@ def _rollback() -> None: logger.error("Update failed and no rollback copy exists; code is unchanged.") return - # Remove files absent from snapshot; skip open files (e.g. active log). + # 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) - # Delete new files inside directories that could not be removed directly. - 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 - + _restore_git() 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) + # Keep the existing history aside rather than deleting it: a failure after + # this point restores it, and the tree itself is replaced by the fetch below. + if path.exists(_GIT_BACKUP): + rmtree(_GIT_BACKUP, onexc=_on_rmtree_error) + if path.isdir(".git"): + rename(".git", _GIT_BACKUP) + elif path.exists(".git"): + remove(".git") # Argument lists, never a shell (no injection); git config is local, not --global. for cmd in ( @@ -134,6 +198,10 @@ 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 + + # The preserved history stays on disk until the whole update has been + # validated: a failure in _validate() afterwards still needs to roll back, + # and by then .git holds only the throwaway repository created above. return True @@ -175,14 +243,23 @@ def _run_update(repo: str, branch: str) -> bool | None: # 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 - # Move config aside for the git reset; a stale backup from a killed run is removed first. - config_backup = path.join("..", f".config.env.{getpid()}.tmp") - if path.exists(config_backup): - remove(config_backup) + # Move config aside so the reset cannot touch it. The name is fixed, not + # per-process: module import already recovered any backup a killed run left, + # so a file still here is this run's own, from a previous attempt. + if path.exists(_CONFIG_BACKUP): + remove(_CONFIG_BACKUP) if path.exists("config.env"): - rename("config.env", config_backup) + rename("config.env", _CONFIG_BACKUP) try: ok = _apply_upstream(repo, branch) @@ -193,11 +270,16 @@ def _run_update(repo: str, branch: str) -> bool | None: if not ok: _rollback() return False + + # The update is complete and valid, so the preserved history is obsolete. + if path.exists(_GIT_BACKUP): + rmtree(_GIT_BACKUP, onexc=_on_rmtree_error) + logger.info("Successfully updated with Latest Updates!") return True finally: - if path.exists(config_backup): - rename(config_backup, "config.env") + if path.exists(_CONFIG_BACKUP): + rename(_CONFIG_BACKUP, "config.env") def main() -> int: From a5705b2aebf24a338b55e61a9a67f495e34e2ea9 Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 12:45:23 +0530 Subject: [PATCH 4/5] build: update in place, and install without assuming pip Applying an update replaced the repository: git init, a throwaway commit, fetch, reset. The user's branches, stashes and remotes went with it. It now fetches and resets in place, so nothing of theirs changes and rollback only has to restore the tree. Dependencies could not install in an environment created by `uv venv`, which has no pip, so an update reported success with new requirements missing. It tries pip then uv, and says what to do when neither works. Test sandboxes copied a virtualenv 24 times a run; excluding it takes the suite from minutes to seconds. --- .github/workflows/tests.yml | 45 +++++---- .gitignore | 5 +- AGENTS.md | 29 +++++- README.md | 7 ++ Thunder/utils/config_parser.py | 5 +- tests/test_ci_workflow.py | 55 +++++++--- tests/test_repo_hygiene.py | 16 ++- tests/test_runtime_safety.py | 60 +++++++++++ tests/test_update_recovery.py | 178 ++++++++++++++++++++++----------- tests/test_update_safety.py | 86 ++++++++++++---- thunder.sh | 25 +++-- update.py | 119 ++++++++++------------ 12 files changed, 437 insertions(+), 193 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c90d36a9..34b82412 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -79,27 +79,21 @@ jobs: 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 - # The smoke test runs the image below. With the container driver that - # build-push-action uses, the result stays in the build cache unless it - # is loaded, so without this `docker run` would find nothing. On a push - # the image is in the registry instead, so loading is unnecessary. - load: ${{ github.event_name != 'push' }} - push: ${{ github.event_name == 'push' }} - tags: fyaz05/thunder:latest + # 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. - # 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 configuration. - env: - # A pull request has the image loaded locally; a push has it in the - # registry, addressed by the digest the build step just produced. - IMAGE: ${{ github.event_name == 'push' && format('fyaz05/thunder@{0}', steps.build.outputs.digest) || 'fyaz05/thunder:latest' }} + # 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 \ @@ -108,5 +102,18 @@ jobs: -e BIN_CHANNEL=-1001234567890 \ -e OWNER_ID=1 \ -e DATABASE_URL=mongodb://localhost:27017/smoke \ - "$IMAGE" python -c \ + 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 35658e24..eee0f579 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ .venv/ venv/ .Python -# Exclude env files (update.py runs `git add .` on self-update); track only the template. +# 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. @@ -35,5 +35,8 @@ wheels/ *.egg .pytest_cache/ .ruff_cache/ +.coverage +.coverage.* +.coverage.json __pycache__/ *.pyc diff --git a/AGENTS.md b/AGENTS.md index f4cff7ab..f4d0fd3f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,7 @@ Copy `config_sample.env` → `config.env`. Required vars: `API_ID`, `API_HASH`, ```bash pip install -r requirements-dev.txt -python -m pytest -q # ~20s; no network or Telegram credentials needed +python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials needed python -m ruff check . # config lives in pyproject.toml ``` @@ -107,6 +107,33 @@ 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 diff --git a/README.md b/README.md index 28794815..b3814715 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,8 @@ 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: @@ -433,6 +435,11 @@ After deployment, to add any additional environment variables, use the Koyeb das > **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 diff --git a/Thunder/utils/config_parser.py b/Thunder/utils/config_parser.py index 5cc7e1ab..fad5caaf 100644 --- a/Thunder/utils/config_parser.py +++ b/Thunder/utils/config_parser.py @@ -1,13 +1,12 @@ """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/tests/test_ci_workflow.py b/tests/test_ci_workflow.py index 039e7ae4..81ec061f 100644 --- a/tests/test_ci_workflow.py +++ b/tests/test_ci_workflow.py @@ -70,7 +70,37 @@ def test_nothing_publishes_before_the_tests_pass(): builds = uses_of(doc, "build", "docker/build-push-action") assert builds, "the build job must build something" for step in builds: - assert PUSH_EVENT in str(step["with"]["push"]), "only a push event may publish" + 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(): @@ -173,20 +203,15 @@ def test_the_built_image_is_actually_run(): "Thunder.vars raises without it and the step would fail on a good image" ) - # The smoke test can only run an image that is somewhere: loaded into the - # local daemon, or pushed to the registry. Pushing covers only the events it - # is true for, so a conditional push needs a load for the other events -- - # without it the container-driver build leaves nothing to run. - push = str(with_.get("push", "")) - load = str(with_.get("load", "")) - pushing_is_conditional = "github.event_name" in push - - assert push in ("true", "false") or pushing_is_conditional, f"unexpected push value: {push!r}" - if with_.get("push") in (None, "false", False) or pushing_is_conditional: - assert "load" in with_, "no push and no load: the smoke test would find no image" - assert load.strip() == "true" or "!= 'push'" in load, ( - f"load must cover the non-push events, got {load!r}" - ) + # 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. diff --git a/tests/test_repo_hygiene.py b/tests/test_repo_hygiene.py index 879a4be4..79ef66d1 100644 --- a/tests/test_repo_hygiene.py +++ b/tests/test_repo_hygiene.py @@ -1,4 +1,9 @@ -"""Verify .gitignore prevents credential leaks during self-update (`update.py` runs `git add .`).""" +"""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 @@ -51,12 +56,13 @@ def test_gitignore_keeps_generated_env_files_out_of_a_self_update_commit(): (tmp / ".env").write_text("API_HASH=secret\n") assert is_git_ignored(tmp, ".env"), "a bare .env must be ignored too" - # Tool caches are created by commands AGENTS.md tells developers to run, - # and update.py runs `git add .`, so neither may be committable. - for cache in (".ruff_cache/0.0.1/index", ".pytest_cache/v/cache/lastfailed"): + # 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} is a regenerable tool cache" + 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 d26b4ee8..69b69f38 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -117,6 +117,66 @@ 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 diff --git a/tests/test_update_recovery.py b/tests/test_update_recovery.py index 4e69a636..3390262a 100644 --- a/tests/test_update_recovery.py +++ b/tests/test_update_recovery.py @@ -1,10 +1,7 @@ -"""Regression tests for the update.py defects found in review. - -Two of the defects covered here destroy data; the test that guards new -behaviour rather than a defect says so in its own docstring. -""" +"""Regression tests for the update.py defects found in review.""" import os import shutil +import stat import subprocess import sys import tempfile @@ -24,31 +21,64 @@ "DATABASE_URL": "mongodb://localhost:27017/t", }) -SKIP = shutil.ignore_patterns("__pycache__", "logs", "*.session*", "config.env", ".git") +# 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 checkout-shaped copy with private history and a config.env to protect. + """A copy of the project with a real git repository and a config.env to protect. - The .git directory is a realistic stub: a rollback test needs to prove the - real thing came back, so it has the files a real repository would have. + 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) - shutil.rmtree(app / ".git", ignore_errors=True) - if history: - git = app / ".git" - (git / "refs" / "heads").mkdir(parents=True) - (git / "HEAD").write_text("ref: refs/heads/main\n") - (git / "config").write_text( - '[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n' - '\turl = https://example.invalid/private.git\n') - (git / "refs" / "heads" / "main").write_text("0" * 40 + "\n") - (git / "CANARY").write_text("private history that must survive\n") + 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 @@ -83,38 +113,64 @@ def run_update(app, upstream, branch="main", timeout=400): def test_a_failed_update_restores_the_original_git_history(): - """The tree must never come back without the history it had before. - - _apply_upstream re-initialises the repository to fetch upstream, so a failure - afterwards used to leave the user with a throwaway one-commit repo and their - branches, remotes and stashes gone. - """ + """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 back after a rollback" + "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/private.git" in config, \ - "the original remotes must be intact" + assert "example.invalid/deploy.git" in config, \ + "the user's own remote must be untouched" assert "thunder@update.local" not in config, \ - "a rollback must not leave the throwaway repository in place" + "no throwaway repository may be created" finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + 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. - This one is not a regression test for a pre-existing defect: the pre-fix code - never preserved history, so it had no backup to leak. It guards the new - behaviour -- that the preserved history is cleaned up and the repository left - behind still works -- which nothing else covers. + 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() @@ -123,18 +179,25 @@ def test_a_successful_update_leaves_a_workable_checkout(): assert result.returncode == 0, result.stderr[-400:] assert (app / "UPSTREAM_MARKER.txt").exists() assert (app / "config.env").read_text().startswith("KEEP_ME") - assert not (deploy_root / "thunder_git_backup").exists(), \ - "the preserved history is obsolete once the update succeeded" 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 + 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: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + force_rmtree(deploy_root) + force_rmtree(upstream_root) def test_config_recovered_when_a_previous_update_was_killed(): @@ -156,20 +219,20 @@ def test_config_recovered_when_a_previous_update_was_killed(): "the stranded config must be recovered, or the bot cannot start" assert not (deploy_root / ".config.env.thunder.tmp").exists() finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + 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. - Previously the missing-.git check only ran when git itself was unusable, so - an unpacked archive was re-initialised as a git repository. + 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: - shutil.rmtree(app / ".git") + force_rmtree(app / ".git") assert not (app / ".git").exists() result = run_update(app, bare) @@ -179,18 +242,17 @@ def test_no_git_checkout_is_not_updated_even_when_git_is_installed(): assert (app / "config.env").read_text().startswith("KEEP_ME") assert not (app / "UPSTREAM_MARKER.txt").exists(), "nothing may be applied" finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + 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 rollback used to exempt a top-level "logs" directory, which never exists - (the real path is Thunder/logs), so the whole Thunder/ tree was deleted. On - Windows the deletion silently failed with WinError 32 and only the log file's - in-use status saved it; on Linux it was removed. The assertion therefore has - to be that the rollback never tries to remove it, which holds on both. + 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() @@ -209,8 +271,8 @@ def test_rollback_keeps_the_open_log_file(): # ...while the code it does not own is still replaced. assert (app / "Thunder" / "utils" / "logger.py").exists() finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + force_rmtree(deploy_root) + force_rmtree(upstream_root) def test_an_unusable_rollback_location_is_reported_not_crashed(): @@ -243,8 +305,8 @@ def test_an_unusable_rollback_location_is_reported_not_crashed(): assert (app / "config.env").read_text().startswith("KEEP_ME") assert not (app / "UPSTREAM_MARKER.txt").exists(), "nothing may be applied" finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + force_rmtree(deploy_root) + force_rmtree(upstream_root) def test_a_stale_file_where_the_rollback_copy_goes_does_not_stop_the_update(): @@ -265,5 +327,5 @@ def test_a_stale_file_where_the_rollback_copy_goes_does_not_stop_the_update(): assert (deploy_root / "thunder_rollback").is_dir(), \ "the rollback copy must be a directory afterwards" finally: - shutil.rmtree(deploy_root, ignore_errors=True) - shutil.rmtree(upstream_root, ignore_errors=True) + force_rmtree(deploy_root) + force_rmtree(upstream_root) diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index 312e8f65..a161f6c9 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -1,6 +1,7 @@ """Verify update.py preconditions and rollback in isolated project copies.""" import os import shutil +import stat import subprocess import sys import tempfile @@ -19,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 @@ -70,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(): @@ -85,14 +124,14 @@ 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: - shutil.rmtree(sandbox / ".git", ignore_errors=True) + force_rmtree(sandbox / ".git") assert not (sandbox / ".git").exists() env = dict(BASE_ENV) @@ -105,7 +144,7 @@ def test_no_git_and_no_checkout_is_not_an_error(): assert (sandbox / "config.env").exists(), "nothing may be touched" assert (sandbox / "update.py").exists(), "code must be left intact" finally: - shutil.rmtree(sandbox, ignore_errors=True) + force_rmtree(sandbox) def test_refuses_unreachable_remote(): @@ -115,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(): @@ -126,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(): @@ -152,8 +198,8 @@ 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(): @@ -168,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 8fe24c8e..3996223d 100644 --- a/update.py +++ b/update.py @@ -1,5 +1,5 @@ from fnmatch import fnmatch -from os import chmod, environ, listdir, path, remove, rename, rmdir +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 @@ -12,12 +12,11 @@ # Rollback state lives beside the tree, so replacing the tree cannot overwrite it. _BACKUP = path.join("..", "thunder_rollback") -_GIT_BACKUP = path.join("..", "thunder_git_backup") _CONFIG_BACKUP = path.join("..", ".config.env.thunder.tmp") # Regenerated or machine-specific, so never part of the code the update replaces. -# "logs" is a directory name: it also covers the live log directory, Thunder/logs, -# whose file is open while this runs. +# 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") @@ -26,7 +25,7 @@ # 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: - rename(_CONFIG_BACKUP, "config.env") + 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}") @@ -43,6 +42,7 @@ def _generated(name: str) -> bool: 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) @@ -129,20 +129,6 @@ def _prune(target: str) -> None: logger.warning(f"Could not remove {target} during rollback: {e}") -def _restore_git() -> None: - """Put the original repository back, discarding the one git init created. - - Only ever called from a failed update. If there is no backup the deployment - had no history to begin with, so what is in .git now is disposable. - """ - if not path.exists(_GIT_BACKUP): - return - if path.exists(".git"): - rmtree(".git", onexc=_on_rmtree_error) - rename(_GIT_BACKUP, ".git") - logger.info("Original git history restored.") - - def _snapshot() -> None: if path.isdir(_BACKUP): rmtree(_BACKUP, onexc=_on_rmtree_error) @@ -165,31 +151,27 @@ def _rollback() -> None: copytree(_BACKUP, ".", dirs_exist_ok=True) - _restore_git() logger.error("Update failed; rolled back to the previous working code.") def _apply_upstream(repo: str, branch: str) -> bool: - # Keep the existing history aside rather than deleting it: a failure after - # this point restores it, and the tree itself is replaced by the fetch below. - if path.exists(_GIT_BACKUP): - rmtree(_GIT_BACKUP, onexc=_on_rmtree_error) - if path.isdir(".git"): - rename(".git", _GIT_BACKUP) - elif path.exists(".git"): - remove(".git") - - # 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: @@ -199,9 +181,6 @@ def _apply_upstream(repo: str, branch: str) -> bool: logger.error(f"git {cmd[1] if len(cmd) > 1 else ''} failed.") return False - # The preserved history stays on disk until the whole update has been - # validated: a failure in _validate() afterwards still needs to roll back, - # and by then .git holds only the throwaway repository created above. return True @@ -209,19 +188,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 @@ -253,13 +245,13 @@ def _run_update(repo: str, branch: str) -> bool | None: f"Nothing has been changed.") return False - # Move config aside so the reset cannot touch it. The name is fixed, not - # per-process: module import already recovered any backup a killed run left, - # so a file still here is this run's own, from a previous attempt. + # 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) @@ -271,15 +263,14 @@ def _run_update(repo: str, branch: str) -> bool | None: _rollback() return False - # The update is complete and valid, so the preserved history is obsolete. - if path.exists(_GIT_BACKUP): - rmtree(_GIT_BACKUP, onexc=_on_rmtree_error) - logger.info("Successfully updated with Latest Updates!") return True finally: + # 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): - rename(_CONFIG_BACKUP, "config.env") + replace(_CONFIG_BACKUP, "config.env") def main() -> int: From cba1ce4a71ee495fed101a8ec7d3627f995b8bb7 Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 13:12:38 +0530 Subject: [PATCH 5/5] docs: correct what the read-only retry is for The comment cited git pack files, which cannot reach this helper any more: _snapshot() copies the tree with .git excluded, so the rollback directory holds no git objects. The retry still earns its place, just for a different file. Measured: a read-only file inside a copied tree makes rmtree raise PermissionError and leave the directory behind; with the chmod retry it is removed. copytree preserves the read-only bit, and the user's own tree can hold such a file, so the helper is still load-bearing on Windows. --- update.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/update.py b/update.py index 3996223d..88b16344 100644 --- a/update.py +++ b/update.py @@ -47,7 +47,9 @@ def _generated_relative(relative: str) -> bool: 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: