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