diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 34b8241..4ef8372 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,12 +29,9 @@ jobs: # 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" + # Must match .python-version and the Dockerfile's minor; + # tests/test_ci_workflow.py asserts that. + python-version: ["3.15"] runs-on: ${{ matrix.os }} timeout-minutes: 20 steps: @@ -43,6 +40,10 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install + # PyYAML has no cp315 wheel; without this it builds its C extension, + # which needs MSVC on Windows. + env: + PYYAML_FORCE_LIBYAML: "0" run: | python -m pip install --upgrade pip pip install -r requirements-dev.txt @@ -103,7 +104,7 @@ jobs: -e OWNER_ID=1 \ -e DATABASE_URL=mongodb://localhost:27017/smoke \ fyaz05/thunder:test python -c \ - "import Thunder, Thunder.__main__, uvloop, tgcrypto, aiohttp; print('ok', Thunder.__version__)" + "import Thunder, Thunder.__main__, uvloop, warpcrypto, 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 diff --git a/.python-version b/.python-version index 3a4f41e..230693c 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.13 \ No newline at end of file +3.15 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index f4d0fd3..992f39a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — Thunder File-to-Link Bot -Python 3.13+ Telegram bot converting files to direct HTTP links. Uses Pyrofork, aiohttp, MongoDB, uvloop. +Python 3.15 Telegram bot converting files to direct HTTP links. Uses wzgram, aiohttp, MongoDB, uvloop. ## Run @@ -15,7 +15,7 @@ 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-pyrofork +# aiohttp, cloudscraper, Jinja2, wzgram, pymongo, psutil, python-dotenv, speedtest-cli # uvloop (non-Windows/Cygwin only, requirements.txt marker); asyncio loop elsewhere ``` @@ -95,15 +95,26 @@ Copy `config_sample.env` → `config.env`. Required vars: `API_ID`, `API_HASH`, ## Testing ```bash -pip install -r requirements-dev.txt +PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials needed python -m ruff check . # config lives in pyproject.toml ``` +PyYAML has no `cp315` wheel, so the env var is required; on Windows set it first, +since `VAR=value cmd` is not valid there: + +```powershell +$env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt +``` + +A cached wheel from an earlier build can make a plain install appear to work — use +`--no-cache-dir` to check. + Covers request parsing, slot conservation and truncation on the streaming routes, the import cycle, database naming, /status before startup, update.py preconditions and rollback, plugin handler registration, the CI -workflow's invariants, and .gitignore hygiene. +workflow's invariants, .gitignore hygiene, and the interpreter and requirements +guards. `pytest` and `ruff` both read `pyproject.toml`; there is no `pytest.ini`. @@ -116,11 +127,13 @@ CI notices a bad upstream release. Every command below was run to confirm it wor 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 +uv venv .venv --python 3.15 # ~0.15s +PYYAML_FORCE_LIBYAML=0 uv pip install --python .venv/bin/python -r requirements-dev.txt uvx ruff check . # ~0.1s, no install needed ``` +The same env var applies to `uv pip install`, which builds the same sdist. + 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. @@ -131,7 +144,7 @@ One caveat if you deploy from this checkout: `uv venv` creates an environment cleanest result comes from seeding pip in the first place: ```bash -uv venv --seed .venv --python 3.13 # includes pip +uv venv --seed .venv --python 3.15 # includes pip ``` ## Debugging diff --git a/Dockerfile b/Dockerfile index 102291b..51ab5c1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.13-slim +FROM python:3.15-slim ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 diff --git a/README.md b/README.md index b381471..2d6887f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@

- -[![Deploy to Railyard](https://app.railyard.run/deploy/badge)](https://app.railyard.run/deploy?repo=https://github.com/fyaz05/FileToLink) Thunder Logo

⚡ Thunder

@@ -10,8 +8,8 @@

- Python Version - Pyrofork + Python Version + wzgram License Telegram Channel

@@ -136,7 +134,7 @@ Copy `config_sample.env` to `config.env` and fill in your values. | `MAX_BATCH_FILES` | Maximum files in batch processing | `50` | | `CHANNEL` | Allow processing messages from channels | `False` | | `BANNED_CHANNELS` | Blocked channel IDs | *(empty)* | -| `SLEEP_THRESHOLD` | Pyrogram flood-wait threshold | `600` | +| `SLEEP_THRESHOLD` | Flood-wait threshold in seconds | `600` | | `WORKERS` | Async workers | `8` | | `NAME` | Bot name; also the MongoDB database name (unsafe chars become `_`) | `ThunderF2L` | | `BIND_ADDRESS` | Bind address | `0.0.0.0` | @@ -287,7 +285,7 @@ This section covers the complete setup process for deploying Thunder, from prere | Requirement | Description | Source | | :--- | :--- | :--- | -| Python 3.13 | Programming language | [python.org](https://python.org) | +| Python 3.15 | Programming language | [python.org](https://python.org) | | MongoDB | Database | [mongodb.com](https://mongodb.com) | | Telegram API | API credentials | [my.telegram.org](https://my.telegram.org/apps) | | Bot Token | From @BotFather | [@BotFather](https://t.me/BotFather) | @@ -578,6 +576,11 @@ A: Your browser likely doesn't support the file's audio or video format (codec). **Q: Why does the bot sometimes become unresponsive?** A: This is likely a **Telegram Flood Wait**. To prevent spam, Telegram temporarily limits accounts that make too many requests. The bot is designed to handle this automatically by pausing and will resume on its own once the limit is lifted. +**Q: On shutdown I see `Task was destroyed but it is pending!` — is something broken?** +A: No, if `✓ Database connection closed` was printed first. The library leaves its media +sessions open on teardown; the bot still exits cleanly. Expect six after a download, none if +nothing was streamed. + #### **Performance** **Q: How can I fix slow download and streaming speeds?** @@ -605,10 +608,15 @@ Contributions are welcome! Please follow these steps: 2. Create a new feature branch (`git checkout -b feature/amazing-feature`). 3. Make your change and run the suite and linter: ```bash - pip install -r requirements-dev.txt + PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX python -m pytest -q python -m ruff check . ``` + The env var is needed on Python 3.15 (no `cp315` wheel). On Windows, where that + assignment is not valid, set it first: + ```powershell + $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt + ``` 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. @@ -622,10 +630,10 @@ Licensed under the [Apache License 2.0](LICENSE). See the `LICENSE` file for det ## Acknowledgments -- [Pyrofork](https://github.com/Mayuri-Chan/pyrofork) - Telegram MTProto API Framework +- [wzgram](https://github.com/rjriajul/wzgram) - 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/wulan17/tgcrypto-pyrofork) - High-performance cryptography library +- [WarpCrypto](https://github.com/rjriajul/warpcrypto) - High-performance cryptography library (Rust) ## ⚠️ Disclaimer diff --git a/Thunder/__init__.py b/Thunder/__init__.py index d9af44e..7e1a281 100644 --- a/Thunder/__init__.py +++ b/Thunder/__init__.py @@ -2,4 +2,4 @@ import time StartTime = time.time() -__version__ = "2.1.0" +__version__ = "2.5.0" diff --git a/Thunder/__main__.py b/Thunder/__main__.py index b9e5ece..20835a4 100644 --- a/Thunder/__main__.py +++ b/Thunder/__main__.py @@ -12,7 +12,7 @@ from pathlib import Path -# Pyrofork binds a client to the loop current at creation and Thunder.bot +# wzgram binds a client to the loop current at creation and Thunder.bot # creates it on import, so the loop has to exist before these imports. try: from uvloop import install diff --git a/pyproject.toml b/pyproject.toml index 76c0a73..bb17b86 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [tool.ruff] line-length = 120 -target-version = "py313" +target-version = "py315" [tool.ruff.lint] # E4 stays out on purpose: __main__.py imports after creating the event loop, diff --git a/requirements-dev.txt b/requirements-dev.txt index b222cda..fd32c8c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,4 +4,6 @@ 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. +# No cp315 wheel: install with PYYAML_FORCE_LIBYAML=0, or the sdist build needs +# MSVC on Windows. pyyaml diff --git a/requirements.txt b/requirements.txt index 08b8461..1cef8b8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,12 +2,10 @@ aiohttp>=3.14 cloudscraper Jinja2 -pyrofork +wzgram pymongo psutil python-dotenv speedtest-cli -# Fork provides cp313/cp314 wheels (avoids C toolchain at build time) and imports as "tgcrypto". -tgcrypto-pyrofork # uvloop is Unix-only; bot falls back to standard asyncio on Windows. uvloop>=0.22.1; sys_platform != "win32" and sys_platform != "cygwin" diff --git a/tests/test_ci_workflow.py b/tests/test_ci_workflow.py index 81ec061..ae3f47d 100644 --- a/tests/test_ci_workflow.py +++ b/tests/test_ci_workflow.py @@ -22,6 +22,10 @@ PINNED_ACTION = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") PUSH_EVENT = "github.event_name == 'push'" +# The interpreter the project ships, read from .python-version rather than written +# twice, so a version bump has one place to change. +PRIMARY_PYTHON = (REPO / ".python-version").read_text(encoding="utf-8").strip() + def load(path: Path): return yaml.safe_load(path.read_text(encoding="utf-8")) @@ -123,18 +127,32 @@ def test_the_suite_runs_on_both_operating_systems(): 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"]] + assert PRIMARY_PYTHON in [str(value) for value in matrix["python-version"]] + +def test_the_tested_python_is_the_one_the_project_ships(): + """`.python-version`, the Dockerfile and CI must name one version. -def test_the_documented_python_range_is_actually_tested(): - """README says 3.13+; a floating dependency can quietly drop the newer one.""" + Three files describe the interpreter and can drift apart silently. + """ 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" - ) + + stated = (REPO / ".python-version").read_text(encoding="utf-8").strip() + + assert stated in tested, \ + f".python-version says {stated!r} but CI tests {sorted(tested)}" + + # Parse FROM rather than reading line 0: a `# syntax=` directive would break + # that, and a substring test would accept a version named only in a comment. + base_images = re.findall(r"^FROM\s+(\S+)", (REPO / "Dockerfile").read_text(encoding="utf-8"), + flags=re.MULTILINE | re.IGNORECASE) + assert base_images, "the Dockerfile has no FROM line" + minor = ".".join(stated.split(".")[:2]) + assert any(re.fullmatch(rf"python:{re.escape(minor)}(\.\d+)?-\w+", image) + for image in base_images), \ + f"the Dockerfile builds from {base_images}, not {minor}" def test_a_weekly_run_guards_the_floating_dependencies(): @@ -256,3 +274,83 @@ def test_dependabot_only_tracks_actions(): assert ecosystems == {"github-actions"}, ( "app dependencies float by policy, so only the pinned actions need updates" ) + + +def test_the_archived_library_stays_out_of_the_requirements(): + """The retired distributions must not return, and wzgram must stay named. + + Nothing else in the tree mentions the old names, so a revert of this file + would be silent until a deployment broke. + """ + def package_name(entry: str) -> str: + # PEP 503: case-insensitive, and -/_/. are interchangeable, so `Pyrofork` + # must not slip past a check for `pyrofork`. + raw = re.split(r"[<>=!~;\[ (]", entry.strip(), maxsplit=1)[0] + return re.sub(r"[-_.]+", "-", raw).lower() + + entries = [ + line.strip() for line in + (REPO / "requirements.txt").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + names = {package_name(entry) for entry in entries} + + for retired in ("pyrofork", "tgcrypto-pyrofork"): + assert retired not in names, f"{retired} is retired; wzgram replaces it" + + assert "wzgram" in names, "wzgram is what the `pyrogram` imports resolve through" + + +def test_the_crypto_backend_is_checked_in_the_image(): + """The smoke test must prove the crypto backend shipped. + + The import list is the only place asserting the backend is present in the + built image, so a stale name there surfaces only when the image fails to start. + """ + steps = workflow()["jobs"]["build"]["steps"] + runs = [step for step in steps if "docker run" in str(step.get("run", ""))] + assert runs, "the image is never run, so nothing proves it starts" + + # Read the parsed `run` values: a commented-out smoke test still matches a + # text search while executing nothing. + commands = " ".join(str(step["run"]) for step in runs) + imports = [line for line in commands.splitlines() if "import Thunder" in line] + assert imports, "the smoke test no longer imports the app" + + assert any("warpcrypto" in line for line in imports), \ + "the smoke test does not import warpcrypto, so nothing proves the backend shipped" + assert not any("tgcrypto" in line for line in imports), \ + "tgcrypto is no longer a dependency; importing it would fail the gate" + + +def test_the_dev_install_is_documented_the_way_ci_does_it(): + """The documented dev installs must match what CI does. + + PyYAML has no cp315 wheel, so the documented install needs the env var or it + fails locally while CI passes. Either spelling counts: `VAR=0 cmd` on POSIX, + `$env:VAR = "0"; cmd` in PowerShell. + """ + # Matches both `PYYAML_FORCE_LIBYAML=0` and `$env:PYYAML_FORCE_LIBYAML = "0"`. + sets_the_var = re.compile(r"PYYAML_FORCE_LIBYAML\s*=\s*[\"']?0") + + for relative in ("requirements-dev.txt", "AGENTS.md", "README.md"): + text = (REPO / relative).read_text(encoding="utf-8") + assert sets_the_var.search(text), ( + f"{relative} no longer tells the reader to set PYYAML_FORCE_LIBYAML=0, " + "so a dev install on 3.15 fails where CI succeeds" + ) + commands = [line.strip() for line in text.splitlines() + if "install" in line and "requirements-dev" in line + and not line.lstrip().startswith("#")] + for command in commands: + assert sets_the_var.search(command), ( + f"{relative} documents `{command}` without setting the env var, " + "which fails on 3.15; both the pip and uv forms need it" + ) + + install = next(step for step in workflow()["jobs"]["test"]["steps"] + if step.get("name") == "Install") + assert (install.get("env") or {}).get("PYYAML_FORCE_LIBYAML") == "0", ( + "the CI install step dropped the env var, so the job would fail on the " + "sdist build it is documented to avoid" + ) diff --git a/tests/test_deployment_entrypoints.py b/tests/test_deployment_entrypoints.py index 65831ef..b181699 100644 --- a/tests/test_deployment_entrypoints.py +++ b/tests/test_deployment_entrypoints.py @@ -21,5 +21,6 @@ def test_platform_files_consumed_at_deploy_time_still_exist(): target = REPO / name assert target.is_file(), f"{name} is read by the deploy platform, not by our code" + # Local tooling and buildpack deploys read this; the Docker image does not. assert (REPO / ".python-version").read_text(encoding="utf-8").strip(), \ - "Heroku reads this to pick the interpreter" + "uv and buildpack-based deploys read this to pick the interpreter" diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index d95c8b0..e1a9c58 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -201,3 +201,57 @@ def test_restart_never_execs_a_path_that_does_not_exist(): 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" + + +def test_update_validation_imports_the_startup_chain_not_just_the_package(): + """Validation must import the names the app uses, and supply configuration. + + Two failures it has to catch, both leaving a tree that compiles: a package + directory left empty by an in-place upgrade, where `import pyrogram` succeeds + and `from pyrogram import Client` fails; and an unresolvable import in a + startup module, which leaves `import Thunder` working while the bot cannot + start. + + And one it must not cause: those modules read configuration when imported, + while `_run_update` moves config.env aside first, so the probe needs + placeholders or it would fail on a good tree and roll it back. + """ + import importlib.util + + spec = importlib.util.spec_from_file_location("_update_under_test", REPO / "update.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + calls = [] + + class FakeCompleted: + returncode = 0 + stderr = b"" + stdout = b"" + + def fake_run(command, **kwargs): + calls.append((command, kwargs)) + return FakeCompleted() + + original = module.srun + try: + module.srun = fake_run + assert module._validate() is True + finally: + module.srun = original + + assert any("compileall" in " ".join(str(a) for a in cmd) for cmd, _ in calls), \ + "syntax checking is still worth doing" + + probe_calls = [(cmd, kw) for cmd, kw in calls if "-c" in cmd] + assert probe_calls, "validation must run an import probe, not only compile" + probe, kwargs = probe_calls[0] + probe = " ".join(str(a) for a in probe) + + for needed in ("from pyrogram import", "Client", "warpcrypto", "Thunder.bot", + "Thunder.__main__"): + assert needed in probe, f"the probe omits {needed}" + + env = kwargs.get("env") or {} + for needed in ("API_ID", "API_HASH", "BOT_TOKEN", "BIN_CHANNEL", "DATABASE_URL"): + assert env.get(needed), f"the probe runs without {needed}" diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index 70769ca..f8a9eb9 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -1,4 +1,6 @@ """Verify update.py preconditions and rollback in isolated project copies.""" +import importlib.util +import sqlite3 import subprocess import sys @@ -6,6 +8,123 @@ run_update) +def _load_update(): + """Import update.py so its helpers can be called directly.""" + from pathlib import Path + + repo = Path(__file__).resolve().parent.parent + spec = importlib.util.spec_from_file_location("_update_under_test", repo / "update.py") + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(repo)) + spec.loader.exec_module(module) + return module + + +SESSIONS_COLS = ("dc_id INTEGER PRIMARY KEY, api_id INTEGER, test_mode INTEGER, " + "auth_key BLOB, date INTEGER, user_id INTEGER, is_bot INTEGER") +SESSIONS_COLS_V7 = SESSIONS_COLS + ", server_address TEXT, port INTEGER" + + +def _write_session(path, version, columns=SESSIONS_COLS, update_state=True, + username_peer_id=False, extra_columns=0): + """Write a session. `columns` shapes it, since the stored version does not + identify the layout: a fixture has to match the format it claims.""" + connection = sqlite3.connect(str(path)) + connection.execute(f"CREATE TABLE sessions ({columns})") + connection.execute( + "CREATE TABLE peers (id INTEGER PRIMARY KEY, access_hash INTEGER, " + "type INTEGER NOT NULL, phone_number TEXT, last_update_on INTEGER)") + connection.execute( + "CREATE TABLE usernames (id INTEGER, username TEXT" + f"{', peer_id INTEGER' if username_peer_id else ''})") + if update_state: + connection.execute( + "CREATE TABLE update_state (id INTEGER PRIMARY KEY, pts INTEGER, " + "qts INTEGER, date INTEGER, seq INTEGER)") + connection.execute("CREATE TABLE version (number INTEGER)") + connection.execute("INSERT INTO version VALUES (?)", (version,)) + placeholders = ", ".join(["2", "123456", "0", "?", "0", "1", "1"] + ["NULL"] * extra_columns) + connection.execute(f"INSERT INTO sessions VALUES ({placeholders})", (b"x" * 256,)) + connection.commit() + connection.close() + + +def test_only_sessions_the_library_cannot_open_are_reported(tmp_path, monkeypatch): + """Report the files the library refuses, not every schema difference. + + A stored version does not identify a session's format: wzgram migrates v6 and + v7, while pyrofork's v4 layout fails to migrate. The library is the only + authority, so update.py tries it on a snapshot. + """ + module = _load_update() + monkeypatch.chdir(tmp_path) + + # pyrofork's shape: its step 4 already created update_state, which wzgram's + # step 4 re-creates without IF NOT EXISTS, so open() raises. + _write_session(tmp_path / "pyrofork.session", 4) + # Migratable: one step behind, shaped as that version leaves it. + _write_session(tmp_path / "migratable.session", 7, SESSIONS_COLS_V7, + username_peer_id=True, extra_columns=2) + _write_session(tmp_path / "current.session", 8, SESSIONS_COLS_V7, + username_peer_id=True, extra_columns=2) + (tmp_path / "garbage.session").write_bytes(b"not a database at all") + (tmp_path / "notes.txt").write_text("ignore me") + + found = module._stale_sessions() + + assert any("pyrofork.session" in entry for entry in found), \ + "a session the library cannot open must be reported" + assert not any("migratable.session" in entry for entry in found), \ + "a session the library migrates must not be reported; deleting it logs the bot out" + assert not any("current.session" in entry for entry in found), \ + "the current session must not be reported" + assert not any("garbage" in entry for entry in found), \ + "a file that is not a session database must be skipped, not crash the update" + assert not any("notes" in entry for entry in found), "only *.session files are sessions" + + +def test_an_uncheckpointed_session_is_not_reported_as_unreadable(tmp_path, monkeypatch): + """A session whose pages are still in the -wal sidecar must survive the check. + + An unclean stop leaves committed schema there and the main file looks empty. + Copying only that file gives the probe no `version` table, so a good session is + reported as incompatible and the operator is told to delete their authorisation. + """ + module = _load_update() + monkeypatch.chdir(tmp_path) + + connection = sqlite3.connect(str(tmp_path / "unclean.session")) + connection.execute("PRAGMA journal_mode=WAL") + connection.execute(f"CREATE TABLE sessions ({SESSIONS_COLS_V7})") + connection.execute( + "CREATE TABLE peers (id INTEGER PRIMARY KEY, access_hash INTEGER, " + "type INTEGER NOT NULL, phone_number TEXT, last_update_on INTEGER)") + connection.execute("CREATE TABLE usernames (id INTEGER, username TEXT, peer_id INTEGER)") + connection.execute( + "CREATE TABLE update_state (id INTEGER PRIMARY KEY, pts INTEGER, " + "qts INTEGER, date INTEGER, seq INTEGER)") + connection.execute("CREATE TABLE version (number INTEGER)") + connection.execute("INSERT INTO version VALUES (8)") + connection.execute( + "INSERT INTO sessions VALUES (2, 123456, 0, ?, 0, 1, 1, NULL, NULL)", + (b"x" * 256,)) + connection.commit() + # Left open and uncheckpointed: the committed pages live in the -wal sidecar, + # which is what an unclean stop leaves behind. + try: + assert (tmp_path / "unclean.session-wal").exists(), \ + "the fixture needs a WAL sidecar to be meaningful" + + found = module._stale_sessions() + + assert not any("unclean.session" in entry for entry in found), ( + "a session readable through its WAL was reported as unreadable; the " + "snapshot must include committed WAL content, not just the main file" + ) + finally: + connection.close() + + def test_refuses_when_upstream_unset(): sandbox = make_sandbox() try: diff --git a/update.py b/update.py index 88b1634..cbb0ee7 100644 --- a/update.py +++ b/update.py @@ -1,10 +1,12 @@ from fnmatch import fnmatch from os import chmod, environ, listdir, path, remove, replace, rmdir -from pathlib import PurePath +from pathlib import Path, PurePath from shutil import copytree, ignore_patterns, rmtree +from sqlite3 import connect as sqlite_connect from stat import S_IWRITE from subprocess import run as srun from sys import executable, exit +from tempfile import TemporaryDirectory from dotenv import load_dotenv @@ -219,7 +221,25 @@ def _install_requirements() -> bool: return True +# Placeholders for the probe below: Thunder.vars validates its configuration at +# import, and _run_update moves config.env aside before validating, so the child +# would otherwise fail on a good tree. The CI smoke test uses the same values. +_PROBE_ENV = { + "API_ID": "123456", + "API_HASH": "0123456789abcdef0123456789abcdef", + "BOT_TOKEN": "123456:AA" + "x" * 30, + "BIN_CHANNEL": "-1001234567890", + "OWNER_ID": "123456", + "DATABASE_URL": "mongodb://localhost:27017/probe", +} + + def _validate() -> bool: + """Confirm the tree compiles and can import what startup needs. + + compileall alone passes on an environment whose packages are broken, so the + import probe is what catches it. + """ try: result = srun( [executable, "-m", "compileall", "-q", "Thunder", "update.py"], @@ -228,7 +248,105 @@ def _validate() -> bool: except OSError as e: logger.error(f"Could not run compileall: {e}") return False - return result.returncode == 0 + if result.returncode != 0: + return False + + try: + # The startup chain, not just the package: an unresolvable import in + # Thunder.bot or Thunder.__main__ compiles and leaves `import Thunder` + # working, while the bot cannot start. Binding names also catches a + # directory left empty by an in-place upgrade (a namespace package). + probe = srun( + [executable, "-c", + "from pyrogram import Client, filters, enums; " + "import warpcrypto, Thunder, Thunder.bot, Thunder.__main__"], + capture_output=True, + env={**environ, **_PROBE_ENV}, + ) + except OSError as e: + logger.error(f"Could not import the application: {e}") + return False + if probe.returncode != 0: + tail = (probe.stderr or b"").decode("utf-8", "replace").strip().splitlines() + logger.error( + "The updated tree cannot import its dependencies: " + f"{tail[-1] if tail else 'no output'}. Recreate the environment " + "(`uv venv --seed .venv`) rather than installing over the old one." + ) + return False + return True + + +def _stale_sessions() -> list[str]: + """*.session files the installed library refuses to open. + + Reported, never deleted: the file holds the bot's authorisation, so the + operator removes it. + + Asked of the library rather than inferred from the stored schema version, which + does not identify the format -- pyrofork's v4 layout fails to migrate while + wzgram migrates v6 and v7. The library is tried on a snapshot, so the original + is untouched. + """ + try: + import asyncio + from pyrogram.storage import FileStorage + except Exception: + return [] + + stale: list[str] = [] + + def snapshot(source: str, destination: str) -> None: + """Write a consistent copy of a SQLite database, WAL included. + + Copying the file alone loses committed pages still in the -wal sidecar, + which an unclean stop leaves behind: the copy then looks corrupt when it is + only uncheckpointed. The backup API reads through the WAL. + """ + origin = sqlite_connect(f"file:{source}?mode=ro", uri=True) + try: + target = sqlite_connect(destination) + try: + origin.backup(target) + finally: + target.close() + finally: + origin.close() + + async def unreadable(source: str) -> bool: + """Snapshot the session, open the copy, and report whether it failed.""" + with TemporaryDirectory(prefix="thunder-session-check-") as holder: + copy = path.join(holder, "probe.session") + try: + snapshot(source, copy) + except Exception: + # Cannot snapshot it, so say nothing: an inconclusive answer must + # not send the operator to delete a session that may be fine. + return False + storage = FileStorage("probe", Path(holder)) + try: + await storage.open() + return False + except Exception: + return True + finally: + try: + await storage.conn.close() + except Exception: + pass + + for name in listdir("."): + if not name.endswith(".session"): + continue + try: + with open(name, "rb") as handle: + if handle.read(15) != b"SQLite format 3": + continue + if asyncio.run(unreadable(name)): + stale.append(name) + except Exception: + continue + return stale def _run_update(repo: str, branch: str) -> bool | None: @@ -266,6 +384,17 @@ def _run_update(repo: str, branch: str) -> bool | None: return False logger.info("Successfully updated with Latest Updates!") + + # Advisory: never turns a good update into a failed one. + try: + for stale in _stale_sessions(): + logger.warning( + f"Session {stale} cannot be read by the installed library; " + "delete it and restart to re-authorise from BOT_TOKEN." + ) + except Exception: + logger.debug("Could not check session compatibility", exc_info=True) + return True finally: # replace, not rename: on Windows rename raises FileExistsError if the