Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(tray): 重启托盘时自动同步依赖、迁移账本并过任务闸门

longmeidaoc792004b954e
diff --git a/scripts/restart_windows_tray.py b/scripts/restart_windows_tray.py
index 134ece268..bca0ddb32 100644
--- a/scripts/restart_windows_tray.py
+++ b/scripts/restart_windows_tray.py
@@ -2,12 +2,20 @@
.venv\\Scripts\\python.exe scripts\\restart_windows_tray.py
+重启前先过任务闸门:本机有重启后续跑不了的任务就拒绝,`--force` 越过。旧托盘退出后、
+新托盘启动前按 `uv.lock` 同步项目 venv;迁移与就绪检查由新托盘启动时执行,结果从
+`<数据根>/state/runtime-prepare.json` 读回来一起报告(ADR-0091)。stdout 只打一行 JSON。
+
+这个进程只能加载标准库与本包的纯 Python 模块:它要在活着的时候替换项目 venv 里的包,
+而 Windows 上被加载的 `.pyd` 换不掉。
+
换生产二进制走 `scripts/deploy_windows_tray.py`,不要单独用这里的 `--swap-from`。
"""
from __future__ import annotations
import argparse
import json
+import socket
import sys
from dataclasses import asdict
from pathlib import Path
@@ -17,11 +25,21 @@ SRC_DIR = PROJECT_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
+from peach.config import DATABASE_PATH, STATE_DIR
+from peach.jobs import process_alive
+from peach.runtime_prepare import Dependencies, RestartPreparation, read_record, task_gate
from peach.windows_restart import (
- DEFAULT_TIMEOUT, find_tray_windows, restart_source_tray, restart_tray,
+ DEFAULT_TIMEOUT, find_tray_windows, restart_source_tray, restart_tray, venv_holders,
)
+def preparation() -> RestartPreparation:
+ return RestartPreparation(
+ Dependencies(PROJECT_ROOT, frozen=False),
+ holders=lambda tray_pid: venv_holders(PROJECT_ROOT / ".venv", (tray_pid,)),
+ )
+
+
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="静默无窗口地重启 Windows Peach 托盘及子服务")
parser.add_argument("--target", type=Path,
@@ -31,19 +49,41 @@ def main(argv: list[str] | None = None) -> int:
help="重启源码部署的托盘(pythonw -m peach.tray),不做换包")
parser.add_argument("--swap-from", type=Path, default=None,
help="旧托盘退出后把这个暂存包换上生产入口,失败自动回退")
+ parser.add_argument("--force", action="store_true",
+ help="有重启后续跑不了的任务也照样重启")
args = parser.parse_args(argv)
# 源码托盘没有生产入口可换,`--swap-from` 在这条路上无处可去。默默忽略它的话,
# 命令照样退出 0、照样打印 ok,而那个包根本没换上——换包失败最不能是静默的。
if args.source and args.swap_from:
parser.error("--source 不能与 --swap-from 同用:源码托盘没有可换的生产入口")
+ gate = task_gate(DATABASE_PATH, host=socket.gethostname(), alive=process_alive)
+ if gate.refused and not args.force:
+ print(json.dumps({"ok": False, "message": gate.refusal(), "tasks": gate.as_dict()},
+ ensure_ascii=False))
+ return 1
+
+ prepare = preparation()
+ timeout = max(1.0, args.timeout)
if not args.source and find_tray_windows(args.target):
- result = restart_tray(args.target, timeout=max(1.0, args.timeout),
- swap_from=args.swap_from)
+ result = restart_tray(args.target, timeout=timeout, swap_from=args.swap_from,
+ prepare=prepare)
else:
- result = restart_source_tray(timeout=max(1.0, args.timeout))
- print(json.dumps(asdict(result), ensure_ascii=False))
- return 0 if result.ok else 1
+ result = restart_source_tray(timeout=timeout, prepare=prepare)
+ payload = asdict(result)
+ payload["tasks"] = gate.as_dict()
+ if result.new_tray_pid is not None:
+ startup = read_record(STATE_DIR, pid=result.new_tray_pid)
+ payload["startup"] = startup
+ if startup is None:
+ payload["message"] += ";未取得新托盘的启动准备记录"
+ elif not startup.get("ok"):
+ failed = ";".join(step["message"] for step in startup.get("steps", ())
+ if step.get("state") in ("failed", "stale"))
+ payload["ok"] = False
+ payload["message"] += f";新托盘启动准备失败:{failed}"
+ print(json.dumps(payload, ensure_ascii=False))
+ return 0 if payload["ok"] else 1
if __name__ == "__main__":
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 7db758c61..3eb140af9 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -68,7 +68,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_subtitles.py", "test_transcodes.py"),
"sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray.py", "test_log_retention.py",
"test_mdns.py", "test_netwatch.py", "test_certs.py",
- "test_review_mirror.py"),
+ "test_review_mirror.py", "test_runtime_prepare.py"),
"metadata": ("test_scraping_access.py", "test_browser_transport.py", "test_metadata*.py", "test_genre_taxonomy.py",
"test_fc2*.py",
"test_community_catalog.py",
@@ -103,7 +103,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",
"test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",
"test_version_bump.py", "test_changelog.py", "test_release_due.py",
- "test_restart_windows_tray.py", "test_deploy_windows_tray.py",
+ "test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py",
"test_buildinfo.py", "test_versioning.py",
"test_windows_update.py", "test_release_updates.py", "test_automatic_updates.py", "test_standalone_update.py", "test_certs.py", "test_config.py",
"test_fsutil.py", "test_desktop_settings.py", "test_desktop_installer.py",
@@ -165,6 +165,10 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"src/peach/tray.py": ("sync", "tooling"),
# 托盘子服务与隧道的 cloudflared 共用这份 Job Object;两边的测试都要跑到。
"src/peach/process_job.py": ("tooling", "sync"),
+ # 托盘重启的实现由 `test_restart_windows_tray.py` 验,模块名推不出来。
+ "src/peach/windows_restart.py": ("tooling",),
+ # 托盘「重启服务」按路径拉起这个脚本(`--source --force`),托盘测试也要跑到。
+ "scripts/restart_windows_tray.py": ("tooling", "sync"),
"src/peach/jav_poster_crop.py": ("metadata", "web"),
# genre 词表按名字只推得出 metadata。复核队列与 API 那两处的用例拿「词表没收的词」
# 当素材:词表一收那个词,`test_web_review.py`(catalog)与 `test_fastapi_api.py`
diff --git a/src/peach/runtime_prepare.py b/src/peach/runtime_prepare.py
new file mode 100644
index 000000000..792b8d9ec
--- /dev/null
+++ b/src/peach/runtime_prepare.py
@@ -0,0 +1,378 @@
+"""子服务起来之前备齐运行环境:项目 venv 与 `uv.lock` 一致,账本迁移到当前结构。
+
+两步都只在子服务停着时做(ADR-0091)。
+
+**依赖。** 判据与动作是同一串参数 `UV_SYNC`,前者多一个 `--check`(只读):
+
+- `--no-install-project` 把 editable 的 peach 本身排除在外。它的 `cache-keys` 含
+ `README.md` 与 `src/peach/__init__.py`,uv 按修改时间判,几乎每次合入都会判成要重装,
+ 而重装要改写 `Scripts\\peach.exe`;源码本来就按 editable 直接读,不需要重装。
+- `--inexact` 不删锁文件之外的包:主检出的 venv 由 `python -m venv` 建,自带 pip。
+- Windows 上被进程加载的 `.pyd` 不能替换,托盘自己就加载着 PIL 与 pystray。所以托盘
+ 进程里只做只读检查;真同步由 `scripts/restart_windows_tray.py` 在旧托盘退出、新托盘
+ 启动之间执行,那时候用这个 venv 的只剩脚本自己,而脚本只加载标准库与本包的纯 Python
+ 模块。本模块因此也只能 import 标准库。
+
+**迁移。** 只有本机是账本写入端才迁,判据与 `library_processing._require_writer` 相同:
+复制关掉时按独立写者;开着时 `device-id` 必须等于 `sync.writer_device`。用子进程跑 venv 的
+`peach migrate`,拿到的一定是检出里的新代码;备份由 `peach migrate upgrade` 自带
+(`ledger.pre-migrate-<时间>.db`),清退归 `peach.ledger_backups`。
+
+**重启闸门。** 重启前看本机还活着的任务:后继由 `requeue_followups` 重排、定时检查到点
+再跑,这两类能续上;其余重启后只会被 `recover_interrupted` 标成 interrupted。
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import sqlite3
+import subprocess
+import sys
+import time
+from contextlib import closing
+from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Callable, Iterable, Mapping
+
+from .fsutil import atomic_write_text
+
+
+#: 判据与动作共用的参数;判据只多一个 `--check`。
+UV_SYNC = ("sync", "--locked", "--all-extras", "--inexact", "--no-install-project")
+#: 托盘启动后把这次准备的结果落在 `<数据根>/state/` 下,重启脚本据此报告新托盘的状况。
+STATE_FILE = "runtime-prepare.json"
+#: 子进程输出只留尾巴进通知与日志:uv 与 migrate 出错时有用的都在最后几行。
+OUTPUT_TAIL = 600
+#: 能续跑的触发方式。后继另按 `followup_key` 判,不在这里。
+RESUMABLE_TRIGGERS = ("scheduled",)
+
+Run = Callable[..., subprocess.CompletedProcess]
+
+
+@dataclass(frozen=True)
+class Step:
+ """一步准备的结果。`state` 取 skipped / current / stale / synced / applied / failed。"""
+
+ name: str
+ state: str
+ message: str
+
+ @property
+ def failed(self) -> bool:
+ return self.state == "failed"
+
+ @property
+ def problem(self) -> bool:
+ """要让人知道的结果:失败,或依赖还没跟上锁文件。"""
+ return self.state in ("failed", "stale")
+
+
+def _tail(completed: subprocess.CompletedProcess) -> str:
+ parts = [str(part).strip() for part in (completed.stdout, completed.stderr) if part]
+ text = "\n".join(part for part in parts if part)
+ return text[-OUTPUT_TAIL:] if text else f"退出码 {completed.returncode},没有输出"
+
+
+def _quiet() -> dict:
+ return {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
+
+
+def find_uv(*, which: Callable[[str], str | None] = shutil.which,
+ environ: Mapping[str, str] | None = None) -> Path | None:
+ """先找 PATH,再找 winget 的安装目录:工具 shell 与开机自启的托盘常缺 WinGet Links。"""
+ found = which("uv")
+ if found:
+ return Path(found)
+ local = (os.environ if environ is None else environ).get("LOCALAPPDATA")
+ if local:
+ packages = Path(local) / "Microsoft" / "WinGet" / "Packages"
+ for candidate in sorted(packages.glob("astral-sh.uv*/uv.exe")):
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+class Dependencies:
+ """项目 venv 与 `uv.lock` 的一致性。`check` 只读,`sync` 真装。"""
+
+ def __init__(self, root: Path, *, run: Run = subprocess.run,
+ which: Callable[[str], str | None] = shutil.which,
+ environ: Mapping[str, str] | None = None, frozen: bool | None = None,
+ clock: Callable[[], float] = time.monotonic) -> None:
+ self.root = Path(root)
+ self._run = run
+ self._which = which
+ self._environ = dict(os.environ if environ is None else environ)
+ self._frozen = getattr(sys, "frozen", False) if frozen is None else frozen
+ self._clock = clock
+
+ def _skip(self) -> tuple[str | None, Path | None]:
+ if self._frozen:
+ return "打包进程不加载项目 venv,依赖由重启脚本核对", None
+ if not (self.root / "uv.lock").is_file():
+ return f"没有 uv.lock:{self.root}", None
+ if not (self.root / ".venv" / "pyvenv.cfg").is_file():
+ return f"没有项目 venv:{self.root / '.venv'}", None
+ uv = find_uv(which=self._which, environ=self._environ)
+ if uv is None:
+ return "未取得 uv:PATH 与 winget 安装目录里都没有", None
+ return None, uv
+
+ def _uv(self, uv: Path, *extra: str) -> subprocess.CompletedProcess:
+ environment = dict(self._environ)
+ # 调用方自己的 venv 不能顶替项目的 `.venv`。
+ for key in ("VIRTUAL_ENV", "UV_PROJECT_ENVIRONMENT"):
+ environment.pop(key, None)
+ environment.update(NO_COLOR="1", UV_NO_PROGRESS="1")
+ return self._run(
+ [str(uv), *UV_SYNC, *extra, "--project", str(self.root)],
+ cwd=str(self.root), capture_output=True, text=True, encoding="utf-8",
+ errors="replace", env=environment, check=False, **_quiet())
+
+ def check(self) -> Step:
+ reason, uv = self._skip()
+ if uv is None:
+ return Step("dependencies", "skipped", reason or "")
+ try:
+ completed = self._uv(uv, "--check")
+ except OSError as exc:
+ return Step("dependencies", "failed", f"uv 没能运行:{exc}")
+ if completed.returncode == 0:
+ return Step("dependencies", "current", "项目 venv 与 uv.lock 一致")
+ output = f"{completed.stdout or ''}\n{completed.stderr or ''}"
+ if "outdated" not in output:
+ return Step("dependencies", "failed", f"核对依赖失败:{_tail(completed)}")
+ wanted = [line.strip()[2:] for line in output.splitlines()
+ if line.strip().startswith("+ ")]
+ listed = "、".join(wanted[:6]) + ("等" if len(wanted) > 6 else "")
+ return Step("dependencies", "stale",
+ f"项目 venv 与 uv.lock 不一致,要装 {len(wanted)} 个包" + (f":{listed}" if listed else ""))
+
+ def sync(self) -> Step:
+ checked = self.check()
+ if checked.state != "stale":
+ return checked
+ _reason, uv = self._skip()
+ started = self._clock()
+ try:
+ completed = self._uv(uv)
+ except OSError as exc:
+ return Step("dependencies", "failed", f"uv 没能运行:{exc}")
+ if completed.returncode != 0:
+ return Step("dependencies", "failed", f"uv sync 失败:{_tail(completed)}")
+ return Step("dependencies", "synced",
+ f"已按 uv.lock 同步依赖({checked.message},用时 {self._clock() - started:.1f} 秒)")
+
+
+def ledger_writer(*, replication_enabled: bool, db: Path, shared_db: Path,
+ state_dir: Path) -> tuple[bool, str]:
+ """本机是不是账本写入端。只读:不像 `sync.device_id` 那样在缺文件时写一个新标识。"""
+ if not replication_enabled:
+ return True, "replication.enabled = false,按独立写者"
+ path = Path(state_dir) / "device-id"
+ try:
+ device = path.read_text(encoding="utf-8").strip()
+ except OSError:
+ device = ""
+ if not device:
+ return False, "本机没有 device-id,判不出是不是写入端"
+ from .sync import writer_device
+ owner = writer_device(Path(db), Path(shared_db))
+ if owner is None:
+ return False, "没有可验证的写入端"
+ if owner != device:
+ return False, f"写入端是 {owner},本机是只读端"
+ return True, "本机是写入端"
+
+
+class Migrations:
+ """用 venv 的 `peach migrate` 子进程把账本迁到当前结构。"""
+
+ def __init__(self, db: Path, *, peach: Callable[[], Path],
+ writer: Callable[[], tuple[bool, str]], run: Run = subprocess.run,
+ environ: Callable[[], Mapping[str, str]] | None = None) -> None:
+ self.db = Path(db)
+ self._peach = peach
+ self._writer = writer
+ self._run = run
+ self._environ = environ or (lambda: os.environ)
+
+ def _migrate(self, executable: Path, *action: str) -> subprocess.CompletedProcess:
+ environment = dict(self._environ())
+ # 子进程的 stdout 被管道捕获时默认走 ANSI 代码页,中文会变成替换字符。
+ environment["PYTHONIOENCODING"] = "utf-8"
+ return self._run(
+ [str(executable), "migrate", *action, "--db", str(self.db)],
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ env=environment, check=False, **_quiet())
+
+ def apply(self) -> Step:
+ if not self.db.is_file():
+ return Step("migrations", "skipped", f"账本不存在:{self.db}")
+ writer, why = self._writer()
+ if not writer:
+ return Step("migrations", "skipped", f"不迁移:{why}")
+ try:
+ executable = self._peach()
+ status = self._migrate(executable, "status")
+ except OSError as exc:
+ return Step("migrations", "failed", f"迁移没能启动:{exc}")
+ if status.returncode != 0:
+ return Step("migrations", "failed", f"migrate status 失败:{_tail(status)}")
+ # `_migrate` 打的是 `migrations: <总数>, pending: <待迁移数>`。
+ found = re.search(r"pending:\s*(\d+)", status.stdout or "")
+ if found is None:
+ return Step("migrations", "failed", f"migrate status 没有报待迁移数:{_tail(status)}")
+ if int(found.group(1)) == 0:
+ return Step("migrations", "current", "账本结构已是最新")
+ try:
+ upgrade = self._migrate(executable, "upgrade", "--yes")
+ except OSError as exc:
+ return Step("migrations", "failed", f"迁移没能启动:{exc}")
+ if upgrade.returncode != 0:
+ return Step("migrations", "failed",
+ f"执行 {found.group(1)} 个待迁移时失败,账本目录里有迁移前备份:"
+ f"{_tail(upgrade)}")
+ applied = re.search(r"^applied:\s*(.+)$", upgrade.stdout or "", re.MULTILINE)
+ backup = re.search(r"^backup:\s*(.+)$", upgrade.stdout or "", re.MULTILINE)
+ return Step("migrations", "applied",
+ f"已执行迁移 {applied.group(1).strip() if applied else found.group(1) + ' 个'}"
+ f",迁移前备份 {backup.group(1).strip() if backup else '未取得'}")
+
+
+def record(state_dir: Path, steps: Iterable[Step], *, pid: int | None = None) -> dict:
+ """把托盘这次启动的准备结果写到 `<数据根>/state/`,重启脚本读它来报告新托盘。"""
+ items = list(steps)
+ payload = {
+ "pid": os.getpid() if pid is None else pid,
+ "at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ "ok": not any(step.problem for step in items),
+ "steps": [asdict(step) for step in items],
+ }
+ directory = Path(state_dir)
+ directory.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(directory / STATE_FILE, json.dumps(payload, ensure_ascii=False, indent=2))
+ return payload
+
+
+def read_record(state_dir: Path, *, pid: int) -> dict | None:
+ """指定那个托盘写下的记录;没有、读不了或是别的进程写的都返回 None。"""
+ try:
+ payload = json.loads((Path(state_dir) / STATE_FILE).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return payload if isinstance(payload, dict) and payload.get("pid") == pid else None
+
+
+@dataclass(frozen=True)
+class ActiveRun:
+ id: int
+ task_key: str
+ trigger: str
+ status: str
+ pid: int | None
+ followup_key: str | None
+
+ def describe(self) -> str:
+ return f"#{self.id} {self.task_key}({self.trigger},{self.status},PID {self.pid})"
+
+
+@dataclass(frozen=True)
+class TaskGate:
+ """重启前本机还活着的任务,分成拦得住重启的与拦不住的。"""
+
+ blocking: tuple[ActiveRun, ...] = ()
+ resumable: tuple[ActiveRun, ...] = ()
+ #: 行还停在活跃状态、进程却已不在:重启伤不到它,下次服务启动会把它标成 interrupted。
+ stale: tuple[ActiveRun, ...] = ()
+ error: str | None = None
+ note: str = ""
+
+ @property
+ def refused(self) -> bool:
+ return bool(self.blocking) or self.error is not None
+
+ def refusal(self) -> str:
+ if self.error is not None:
+ return f"拒绝重启:读不了任务表({self.error});确认没有任务在跑后加 --force"
+ listed = "、".join(run.describe() for run in self.blocking)
+ return f"拒绝重启:这些任务重启后续跑不了:{listed};等它们结束,或加 --force"
+
+ def as_dict(self) -> dict:
+ return {
+ "blocking": [asdict(run) for run in self.blocking],
+ "resumable": [asdict(run) for run in self.resumable],
+ "stale": [asdict(run) for run in self.stale],
+ "error": self.error,
+ "note": self.note,
+ }
+
+
+def task_gate(db: Path, *, host: str, alive: Callable[[int], bool]) -> TaskGate:
+ """只读查 `task_run`,把本机的活跃行分类。"""
+ db = Path(db)
+ if not db.is_file():
+ return TaskGate(note=f"账本不存在:{db}")
+ try:
+ with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=ro", uri=True,
+ timeout=2)) as connection:
+ connection.execute("PRAGMA query_only=ON")
+ rows = connection.execute(
+ "SELECT id, task_key, trigger, status, pid, followup_key FROM task_run "
+ "WHERE status IN ('pending','running') AND host=? ORDER BY id",
+ (host,)).fetchall()
+ except sqlite3.OperationalError as exc:
+ if "no such table" in str(exc) or "no such column" in str(exc):
+ return TaskGate(note=f"账本里还没有可判的任务表:{exc}")
+ return TaskGate(error=str(exc))
+ except sqlite3.Error as exc:
+ return TaskGate(error=str(exc))
+ blocking: list[ActiveRun] = []
+ resumable: list[ActiveRun] = []
+ stale: list[ActiveRun] = []
+ for row in rows:
+ run = ActiveRun(int(row[0]), str(row[1]), str(row[2]), str(row[3]),
+ None if row[4] is None else int(row[4]), row[5])
+ if run.followup_key or run.trigger in RESUMABLE_TRIGGERS:
+ resumable.append(run)
+ elif run.pid is not None and not alive(run.pid):
+ stale.append(run)
+ else:
+ blocking.append(run)
+ return TaskGate(tuple(blocking), tuple(resumable), tuple(stale))
+
+
+@dataclass
+class RestartPreparation:
+ """`windows_restart` 在旧托盘停下前后各调一次的准备步骤,只管依赖。
+
+ 迁移不在这里:新托盘启动时自己会跑,它的数据根与环境变量才是服务真正用的那一份。
+ `holders(tray_pid)` 返回旧托盘那棵进程树以外、还在用项目 venv 的进程;要同步依赖时
+ 有这种进程就拒绝重启,因为它们加载着的 `.pyd` 换不掉,uv 会在半路失败。
+ """
+
+ dependencies: Dependencies
+ holders: Callable[[int], tuple[int, ...]]
+ checked: Step | None = None
+ synced: Step | None = None
+
+ def before_stop(self, tray_pid: int) -> str | None:
+ self.checked = self.dependencies.check()
+ if self.checked.state != "stale":
+ return None
+ holding = self.holders(tray_pid)
+ if holding:
+ listed = "、".join(str(pid) for pid in holding)
+ return (f"拒绝重启:{self.checked.message},但这些进程还在用项目 venv:"
+ f"PID {listed};先停掉它们再重启")
+ return None
+
+ def while_stopped(self) -> tuple[bool, str | None]:
+ if self.checked is None or self.checked.state != "stale":
+ return (self.checked is None or not self.checked.failed,
+ self.checked.message if self.checked else None)
+ self.synced = self.dependencies.sync()
+ return not self.synced.failed, self.synced.message
diff --git a/src/peach/tray.py b/src/peach/tray.py
index a46c0282a..8a7bc92db 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import argparse
import ctypes
+import json
import logging
import os
import re
@@ -18,7 +19,7 @@ import httpx
import pystray
from PIL import Image
-from . import ledger_backups, log_retention, onboarding, settings_file
+from . import ledger_backups, log_retention, onboarding, runtime_prepare, settings_file
from .appid import MACOS_LAUNCH_AGENT_LABEL
from .certs import ensure_certificate
from .distribution import standalone
@@ -89,6 +90,17 @@ TRAY_SOURCES = (
)
+#: `/healthz?ready=1` 各项检查给人看的名字(`peach.health.readiness`)。
+READINESS_LABELS = {
+ "configured": "未初始化", "web": "页面文件缺失", "database": "账本打不开",
+ "schema": "账本结构与迁移不一致",
+}
+
+#: 托盘拉起的整托盘重启脚本最多等多久。脚本停旧托盘、同步依赖、起新托盘各有期限,
+#: 本托盘还活着地等过这么久,说明脚本卡在停托盘之前,菜单动作锁要放开。
+TRAY_RESTART_WAIT = 300.0
+
+
def tray_restart_required(changed_paths: tuple[str, ...]) -> bool:
"""这次更新动没动托盘自己的代码。"""
return any(path in TRAY_SOURCES for path in changed_paths)
@@ -357,11 +369,41 @@ class ServiceManager:
process.kill()
process.wait(timeout=3)
- def restart(self) -> bool:
+ def restart(self, prepare: Callable[[], object] | None = None) -> bool:
+ """停掉自己的子服务,`prepare` 在它们都停着时执行(迁移),再拉起来等就绪。"""
self.stop_owned()
+ if prepare is not None:
+ prepare()
self.start_missing()
return self.wait_until_ready()
+ def readiness_problems(self) -> list[str]:
+ """逐个问 `/healthz?ready=1`,返回没就绪的那几条;全就绪返回空列表。
+
+ 只有 API 服务报 `ready`:80 口的跳转服务忽略这个参数、只回 `ok`,没有 `ready`
+ 字段的回应不算数。`healthy()` 看的是 `ok`,账本结构落后时服务照样回 `ok`,
+ 所以这里另问一遍,校验方式与健康检查相同(项目 CA)。
+ """
+ problems: list[str] = []
+ for spec in self.specs:
+ try:
+ response = self._health_get(
+ f"{spec.health_url}?ready=1", timeout=3.0, verify=spec.verify,
+ trust_env=False,
+ )
+ payload = response.json()
+ except (httpx.HTTPError, OSError, ValueError, AttributeError) as exc:
+ problems.append(f"{spec.name.upper()} 就绪检查无响应({exc})")
+ continue
+ if not isinstance(payload, dict) or "ready" not in payload:
+ continue
+ if payload.get("ready") is not True:
+ checks = payload.get("checks") or {}
+ failed = [READINESS_LABELS.get(key, key) for key, ok in checks.items() if not ok]
+ detail = "、".join(failed) or f"状态码 {response.status_code}"
+ problems.append(f"{spec.name.upper()} 未就绪:{detail}")
+ return problems
+
@staticmethod
def _current_ledger_plan() -> SyncPlan:
return resolve(DATABASE_PATH, SHARED_DATABASE_PATH, device_id(STATE_DIR))
@@ -494,6 +536,89 @@ def _peach_executable() -> Path:
raise FileNotFoundError(f"{_EXECUTABLE} is missing; reinstall the editable project")
+def spawn_tray_restart(
+ log_path: Path, *, popen: Callable[..., subprocess.Popen] = subprocess.Popen,
+ root: Path = PROJECT_ROOT,
+) -> subprocess.Popen:
+ """从托盘里分离地拉起 `restart_windows_tray.py --source --force`。
+
+ 脚本要比本托盘活得久:它给本托盘发停止消息,等本托盘与子服务退净后同步依赖,再起
+ 新托盘。所以不挂进子服务那个 kill-on-close Job。`--force`:点「重启服务」本来就要停
+ 子服务,任务闸门在这条路上不拦。输出追加进 `log_path`,脚本没走到停托盘那一步就退出
+ 时,托盘从最后一行读出原因。
+ """
+ python = root / ".venv" / _BIN_DIR / ("python.exe" if os.name == "nt" else "python")
+ script = root / "scripts" / "restart_windows_tray.py"
+ for required in (python, script):
+ if not required.is_file():
+ raise FileNotFoundError(f"整托盘重启缺少 {required}")
+ environment = os.environ.copy()
+ environment["PYTHONIOENCODING"] = "utf-8"
+ flags = 0
+ if os.name == "nt":
+ flags = (subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW
+ | subprocess.CREATE_NEW_PROCESS_GROUP)
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ with log_path.open("ab") as output:
+ return popen(
+ [str(python), "-X", "utf8", str(script), "--source", "--force"],
+ cwd=str(root), stdin=subprocess.DEVNULL, stdout=output,
+ stderr=subprocess.STDOUT, shell=False, env=environment, creationflags=flags,
+ )
+
+
+def last_reported_message(log_path: Path) -> str | None:
+ """重启脚本最后一行输出里的 `message`;不是 JSON 就原样返回那一行。"""
+ try:
+ lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ return None
+ for line in reversed(lines):
+ text = line.strip()
+ if not text:
+ continue
+ try:
+ return str(json.loads(text).get("message") or text)
+ except (ValueError, AttributeError):
+ return text[-runtime_prepare.OUTPUT_TAIL:]
+ return None
+
+
+@dataclass(frozen=True)
+class TrayPreparation:
+ """托盘那一侧的运行环境准备(ADR-0091),由 `main()` 装配后交给 `PeachTray`。
+
+ 不注入就什么都不做:测试里的托盘不会去碰真实账本,macOS 菜单栏也不走这里。
+ `dependencies` 只读核对(`check()`),`migrations` 在子服务停着时真跑(`apply()`)。
+ """
+
+ dependencies: object
+ migrations: object
+ state_dir: Path
+ restart_log: Path
+ spawn_restart: Callable[[], subprocess.Popen]
+
+
+def tray_preparation(config, manager: "ServiceManager") -> TrayPreparation:
+ database = config.directory("database") / "ledger.db"
+ state = config.directory("state")
+ restart_log = config.directory("logs") / "tray-restart.out.log"
+ shared = config.shared_root / "database" / "ledger.db"
+ return TrayPreparation(
+ dependencies=runtime_prepare.Dependencies(PROJECT_ROOT),
+ migrations=runtime_prepare.Migrations(
+ database, peach=_peach_executable,
+ writer=lambda: runtime_prepare.ledger_writer(
+ replication_enabled=bool(config.replication.enabled) and not standalone(),
+ db=database, shared_db=shared, state_dir=state),
+ environ=manager.child_environment,
+ ),
+ state_dir=state,
+ restart_log=restart_log,
+ spawn_restart=lambda: spawn_tray_restart(restart_log),
+ )
+
+
def build_macos_service_specs(
*,
tls_dir: Path | None = None,
@@ -846,10 +971,12 @@ class PeachTray:
gate: "SetupGate | None" = None,
silent: bool = False,
show_browser: bool = False,
+ preparation: TrayPreparation | None = None,
) -> None:
self.manager = manager
self.silent = silent
self.show_browser = show_browser
+ self.preparation = preparation
self.gate = gate or SetupGate(manager, settings_file.active(), waiting=False)
self.versions = versions or VersionManager()
self.windows_updates = windows_updates or WindowsUpdateInstaller(
@@ -895,19 +1022,104 @@ class PeachTray:
# 等待首次设置时打开的是引导服务的表单,不是那个还没有人在监听的 `.local`。
self.gate.open()
+ # -- 运行环境准备(ADR-0091)------------------------------------------
+
+ def _check_dependencies(self) -> "runtime_prepare.Step | None":
+ if self.preparation is None:
+ return None
+ step = self.preparation.dependencies.check()
+ if step.problem:
+ LOGGER.warning("依赖:%s", step.message)
+ return step
+
+ def _migrate(self) -> "runtime_prepare.Step | None":
+ """子服务停着时把账本迁到当前结构。首次设置没走完时还没有正式账本,不迁。"""
+ if self.preparation is None or self.gate.waiting:
+ return None
+ step = self.preparation.migrations.apply()
+ (LOGGER.error if step.failed else LOGGER.info)("迁移:%s", step.message)
+ return step
+
+ def _readiness(self) -> "runtime_prepare.Step | None":
+ if self.preparation is None or self.gate.waiting:
+ return None
+ problems = self.manager.readiness_problems()
+ if problems:
+ LOGGER.error("就绪检查:%s", ";".join(problems))
+ return runtime_prepare.Step("readiness", "failed", ";".join(problems))
+ return runtime_prepare.Step("readiness", "current", "服务已就绪")
+
+ def _record(self, steps: list) -> list[str]:
+ """落一份准备记录,返回要告诉人的那几条。"""
+ steps = [step for step in steps if step is not None]
+ if self.preparation is not None:
+ try:
+ runtime_prepare.record(self.preparation.state_dir, steps)
+ except OSError:
+ LOGGER.warning("运行环境准备记录写不进去", exc_info=True)
+ return [step.message + (";点托盘「重启服务」会整体重启托盘并同步依赖"
+ if step.state == "stale" else "")
+ for step in steps if step.problem]
+
+ def _restart_whole_tray(self, tray_icon, reason) -> bool:
+ """依赖要换就整托盘重启:本进程加载着 venv 里的 `.pyd`,活着的托盘里同步不了。
+
+ 返回 True 表示交给了重启脚本(它会停掉本托盘,或者迟迟没有结果);False 表示
+ 脚本没起来或拒绝了这次重启,调用方照常只重启子服务。
+ """
+ tray_icon.notify(f"{reason.message},正在整体重启托盘以同步依赖…", "Peach")
+ try:
+ process = self.preparation.spawn_restart()
+ except OSError as exc:
+ LOGGER.error("整托盘重启没能启动:%s", exc)
+ tray_icon.notify(f"整体重启托盘没能启动({exc}),只重启子服务。", "Peach")
+ return False
+ try:
+ process.wait(timeout=TRAY_RESTART_WAIT)
+ except subprocess.TimeoutExpired:
+ tray_icon.notify("整体重启托盘还没有结果,详情见 tray-restart.out.log。", "Peach")
+ return True
+ # 走到这里说明脚本已经退出、本托盘却还活着:重启被拒,或在停托盘之前就失败了。
+ message = (last_reported_message(self.preparation.restart_log)
+ or f"退出码 {process.returncode}")
+ LOGGER.error("整托盘重启没有完成:%s", message)
+ tray_icon.notify(f"整体重启托盘没有完成:{message}。只重启子服务。", "Peach")
+ return False
+
+ def _restart_services(self, tray_icon) -> tuple[bool | None, list[str]]:
+ """停子服务、迁移、再拉起并检查就绪。返回 (是否恢复, 要告诉人的问题)。
+
+ 依赖与锁文件不一致时先交给整托盘重启,交出去了就返回 (None, [])。
+ """
+ dependencies = self._check_dependencies()
+ if (dependencies is not None and dependencies.state == "stale"
+ and self._restart_whole_tray(tray_icon, dependencies)):
+ return None, []
+ migrated: list = []
+ prepare = (lambda: migrated.append(self._migrate())) if self.preparation else None
+ ready = self.manager.restart(prepare=prepare)
+ readiness = [self._readiness()] if ready else []
+ return ready, self._record([dependencies, *migrated, *readiness])
+
def restart(self, icon=None, _item=None) -> None:
if not self._action_lock.acquire(blocking=False):
return
+ tray_icon = icon or self.icon
def work() -> None:
try:
- ready = self.manager.restart()
+ ready, problems = self._restart_services(tray_icon)
+ if ready is None:
+ return
if self._stop_event.is_set():
self.manager.stop_owned()
return
- (icon or self.icon).update_menu()
+ tray_icon.update_menu()
if not ready:
- (icon or self.icon).notify("服务未能在 20 秒内恢复,请查看日志。", "Peach")
+ tray_icon.notify(";".join(["服务未能在 20 秒内恢复,请查看日志", *problems])
+ + "。", "Peach")
+ elif problems:
+ tray_icon.notify("服务已重启,但" + ";".join(problems), "Peach")
finally:
self._action_lock.release()
@@ -1023,10 +1235,14 @@ class PeachTray:
tray_icon.stop()
return
- ready = self.manager.restart()
+ ready, problems = self._restart_services(tray_icon)
+ if ready is None:
+ return
if ready:
self.windows_updates.clear_pending()
suffix = "服务已重启。" if ready else "服务未能恢复,请查看日志。"
+ if problems:
+ suffix += "但" + ";".join(problems) + "。"
tray_icon.update_menu()
tray_icon.notify(f"{prepared.message}{suffix}", "Peach 开发进度")
finally:
@@ -1108,6 +1324,9 @@ class PeachTray:
icon.notify(self._startup_warning, "Peach")
def run(self) -> None:
+ # 迁移排在第一次拉起子服务之前:服务查到还没建的表就是 500。依赖只读核对,
+ # 托盘自己已经加载着这个 venv,换不了包。
+ startup = [self._check_dependencies(), self._migrate()]
self.manager.start_missing()
# 上一次更新留下的备份与暂存构建在这里清退:替换助手结束时托盘已经不在,
# 只有下一次启动能确认「新托盘已经活下来、旧备份可以少留一份」。
@@ -1128,8 +1347,14 @@ class PeachTray:
self._startup_warning = "首次设置服务没能启动,请查看日志。"
elif not self.manager.wait_until_ready():
self._startup_warning = "Peach 只启动了部分服务,请查看托盘状态和日志。"
- elif self.show_browser:
- self.gate.open()
+ else:
+ startup.append(self._readiness())
+ if self.show_browser:
+ self.gate.open()
+ problems = self._record(startup)
+ if problems:
+ self._startup_warning = ";".join(
+ part for part in (self._startup_warning, *problems) if part)
threading.Thread(target=self._monitor, name="PeachHealth", daemon=True).start()
logging.getLogger(__name__).info("托盘启动完成:%s", self.manager.status())
try:
@@ -1442,7 +1667,8 @@ def main(argv: list[str] | None = None) -> int:
manager.start_missing()
run_macos_menu_bar(manager, gate, silent=args.silent, show_browser=args.show)
else:
- PeachTray(manager, gate=gate, silent=args.silent, show_browser=args.show).run()
+ PeachTray(manager, gate=gate, silent=args.silent, show_browser=args.show,
+ preparation=tray_preparation(config, manager)).run()
except Exception as exc:
show_message("Peach 启动失败", str(exc), error=True)
return 1
diff --git a/src/peach/windows_restart.py b/src/peach/windows_restart.py
index 35de3a2ba..cec431c84 100644
--- a/src/peach/windows_restart.py
+++ b/src/peach/windows_restart.py
@@ -15,7 +15,7 @@ import time
from ctypes import wintypes
from dataclasses import dataclass
from pathlib import Path
-from typing import Callable, Iterable
+from typing import Callable, Iterable, Protocol
from .windows_update import replace_with_retry, swap_tray_binary
@@ -42,6 +42,8 @@ class RestartResult:
service_pids: tuple[int, ...] = ()
swapped_from: str | None = None
backup: str | None = None
+ #: 旧托盘停着的那段时间里做的准备(依赖同步)给人看的一句话;没做就是 None。
+ preparation: str | None = None
def _normal_path(path: str | Path) -> str:
@@ -315,6 +317,41 @@ def owned_service_pids(tray_process_id: int, service_executable: Path) -> tuple[
))
+def venv_holders(
+ venv: Path,
+ trees: Iterable[int],
+ *,
+ own_pid: int | None = None,
+ snapshot: Callable[[], tuple[dict[int, str], dict[int, int]]] | None = None,
+) -> tuple[int, ...]:
+ """映像在项目 venv 里、又不归给定进程树管的进程。
+
+ 给定的树(旧托盘)连同祖先与子孙都不算:托盘退出时它们一起走。本进程和它的祖先也
+ 不算:重启脚本自己就是 venv 的 `python.exe` 启动器拉起来的,从托盘菜单发起时托盘
+ 还是它的祖先。venv 启动器拉起的基础解释器映像不在 venv 里,列出启动器就够认人了。
+ """
+ if snapshot is None:
+ if os.name != "nt":
+ return ()
+ snapshot = _process_paths_and_parents
+ paths, parents = snapshot()
+ prefix = _normal_path(venv).rstrip("\\/") + os.sep
+ roots = tuple(int(pid) for pid in trees)
+ exempt: set[int] = set()
+ for root in (os.getpid() if own_pid is None else own_pid, *roots):
+ current, seen = root, set()
+ while current and current not in seen:
+ exempt.add(current)
+ seen.add(current)
+ current = parents.get(current, 0)
+ exempt.update(pid for pid in paths
+ if any(_descends_from(pid, root, parents) for root in roots))
+ return tuple(sorted(
+ pid for pid, path in paths.items()
+ if pid not in exempt and _normal_path(path).startswith(prefix)
+ ))
+
+
def stray_service_pids(tray_process_id: int, service_executable: Path) -> tuple[int, ...]:
"""不在这个托盘名下的 `peach serve`:被强杀的托盘留下的孤儿就在这里面。
@@ -477,11 +514,33 @@ def _rolled_back(
backup=str(backup))
+class Preparation(Protocol):
+ """旧托盘停下前后各调一次的准备步骤(`runtime_prepare.RestartPreparation`)。
+
+ `before_stop` 返回拒绝理由就什么都不动;`while_stopped` 在旧托盘与它的子服务都退净、
+ 新托盘还没起的窗口里执行,返回 (是否备齐, 给人看的一句话)。没备齐也照样起新托盘:
+ 别把机器留在没有托盘的状态,失败写进结果。
+ """
+
+ def before_stop(self, tray_pid: int) -> str | None: ...
+
+ def while_stopped(self) -> tuple[bool, str | None]: ...
+
+
+def _finished(ok: bool, message: str, prepared: tuple[bool, str | None],
+ **fields) -> RestartResult:
+ ready, note = prepared
+ if ok and not ready:
+ ok, message = False, f"{message},但运行环境没有备齐:{note}"
+ return RestartResult(ok, message, preparation=note, **fields)
+
+
def restart_tray(
target: Path,
*,
timeout: float = DEFAULT_TIMEOUT,
swap_from: Path | None = None,
+ prepare: Preparation | None = None,
find_windows: Callable[[Path], tuple[TrayWindow, ...]] = find_tray_windows,
stop_window: Callable[[int], bool] = post_stop,
alive: Callable[[int], bool] = process_alive,
@@ -503,12 +562,16 @@ def restart_tray(
if len(process_ids) != 1 or not windows:
return RestartResult(False, "拒绝重启:没有找到唯一且路径匹配的 Peach 托盘窗口")
old_process_id = next(iter(process_ids))
+ refusal = prepare.before_stop(old_process_id) if prepare is not None else None
+ if refusal:
+ return RestartResult(False, refusal, old_tray_pid=old_process_id)
stopped = _stop_old_tray(
windows, old_process_id, service_executable, timeout=timeout,
stop_window=stop_window, alive=alive, services=services, strays=strays, sleep=sleep)
if stopped is not None:
return stopped
+ prepared = prepare.while_stopped() if prepare is not None else (True, None)
backup: Path | None = None
if swap_from is not None:
try:
@@ -529,8 +592,8 @@ def restart_tray(
start(target), lambda: find_windows(target), service_executable,
timeout=timeout, services=services, sleep=sleep)
if launch.ready:
- return RestartResult(
- True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
+ return _finished(
+ True, "托盘已正常重启并重新拥有 HTTP/HTTPS 子服务", prepared,
old_tray_pid=old_process_id, new_tray_pid=launch.tray_pid,
service_pids=launch.service_pids, swapped_from=swapped_from,
backup=backup_path,
@@ -539,8 +602,8 @@ def restart_tray(
return _rolled_back(
backup, target, start=start, sleep=sleep, message=launch.failure(),
old_tray_pid=old_process_id, swapped_from=swapped_from)
- return RestartResult(False, launch.failure(), old_tray_pid=old_process_id,
- new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
+ return _finished(False, launch.failure(), prepared, old_tray_pid=old_process_id,
+ new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
def restart_source_tray(
@@ -554,6 +617,7 @@ def restart_source_tray(
services: Callable[[int, Path], tuple[int, ...]] = owned_service_pids,
strays: Callable[[int, Path], tuple[int, ...]] = stray_service_pids,
sleep: Callable[[float], None] = time.sleep,
+ prepare: Preparation | None = None,
) -> RestartResult:
"""源码部署托盘的正常重启:按同一命令行自起新托盘。
@@ -589,18 +653,22 @@ def restart_source_tray(
if not service_executable.is_file():
return RestartResult(False, f"拒绝重启:源码托盘旁没有服务入口 {service_executable}",
old_tray_pid=old_process_id)
+ refusal = prepare.before_stop(old_process_id) if prepare is not None else None
+ if refusal:
+ return RestartResult(False, refusal, old_tray_pid=old_process_id)
stopped = _stop_old_tray(
windows, old_process_id, service_executable, timeout=timeout,
stop_window=stop_window, alive=alive, services=services, strays=strays, sleep=sleep)
if stopped is not None:
return stopped
+ prepared = prepare.while_stopped() if prepare is not None else (True, None)
launch = _await_new_tray(
start_argv(argv), find_windows, service_executable,
timeout=timeout, services=services, sleep=sleep)
if launch.ready:
- return RestartResult(True, "源码托盘已正常重启并重新拥有 HTTP/HTTPS 子服务",
- old_tray_pid=old_process_id, new_tray_pid=launch.tray_pid,
- service_pids=launch.service_pids)
- return RestartResult(False, launch.failure(), old_tray_pid=old_process_id,
- new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
+ return _finished(True, "源码托盘已正常重启并重新拥有 HTTP/HTTPS 子服务", prepared,
+ old_tray_pid=old_process_id, new_tray_pid=launch.tray_pid,
+ service_pids=launch.service_pids)
+ return _finished(False, launch.failure(), prepared, old_tray_pid=old_process_id,
+ new_tray_pid=launch.tray_pid, service_pids=launch.service_pids)
diff --git a/tests/test_restart_windows_tray.py b/tests/test_restart_windows_tray.py
index f661344b0..ee57b7001 100644
--- a/tests/test_restart_windows_tray.py
+++ b/tests/test_restart_windows_tray.py
@@ -11,7 +11,7 @@ import unittest
from pathlib import Path
from unittest import mock
-from peach import windows_restart
+from peach import runtime_prepare, windows_restart
ROOT = Path(__file__).resolve().parents[1]
@@ -330,7 +330,156 @@ class RestartWindowsTrayTests(unittest.TestCase):
self.assertEqual(start.call_count, 2)
+class Preparation:
+ """记下准备步骤与停、起托盘的先后。"""
+
+ def __init__(self, events, *, refusal=None, ready=True, note="已按 uv.lock 同步依赖"):
+ self.events, self.refusal, self.ready, self.note = events, refusal, ready, note
+
+ def before_stop(self, tray_pid):
+ self.events.append(("check", tray_pid))
+ return self.refusal
+
+ def while_stopped(self):
+ self.events.append("sync")
+ return self.ready, self.note
+
+
+class RestartPreparationTests(unittest.TestCase):
+ BOOTSTRAP = RestartWindowsTrayTests.BOOTSTRAP
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ root = Path(self.temp.name).resolve()
+ self.pythonw = root / ".venv" / "Scripts" / "pythonw.exe"
+ self.service = self.pythonw.with_name("peach.exe")
+ self.pythonw.parent.mkdir(parents=True)
+ self.pythonw.write_bytes(b"shim")
+ self.service.write_bytes(b"service")
+ self.argv = [str(self.pythonw), "-c", self.BOOTSTRAP, "--silent"]
+
+ def tearDown(self):
+ self.temp.cleanup()
+
+ def restart(self, preparation, events):
+ windows = iter((
+ (windows_restart.TrayWindow(10, 20),),
+ (windows_restart.TrayWindow(30, 40),),
+ ))
+ launched = mock.Mock()
+ launched.poll.return_value = None
+ return windows_restart.restart_source_tray(
+ find_windows=lambda: next(windows),
+ stop_window=lambda _handle: events.append("stop") or True,
+ alive=lambda _pid: False,
+ command_lines=lambda: {10: subprocess.list2cmdline(self.argv)},
+ start=lambda argv: events.append("start") or launched,
+ services=lambda tray_pid, _executable: (51, 52) if tray_pid == 30 else (),
+ sleep=lambda _seconds: None,
+ prepare=preparation,
+ )
+
+ def test_dependencies_are_synced_after_the_old_tray_stops_and_before_the_new_starts(self):
+ events = []
+ result = self.restart(Preparation(events), events)
+ self.assertTrue(result.ok, result.message)
+ self.assertEqual(events, [("check", 10), "stop", "sync", "start"])
+ self.assertEqual(result.preparation, "已按 uv.lock 同步依赖")
+
+ def test_a_refusal_stops_nothing(self):
+ events = []
+ result = self.restart(Preparation(events, refusal="拒绝重启:PID 48420 还在用项目 venv"),
+ events)
+ self.assertFalse(result.ok)
+ self.assertIn("48420", result.message)
+ self.assertEqual(events, [("check", 10)])
+
+ def test_a_failed_sync_still_brings_the_tray_back_and_says_so(self):
+ events = []
+ result = self.restart(Preparation(events, ready=False, note="uv sync 失败"), events)
+ self.assertEqual(events[-1], "start")
+ self.assertFalse(result.ok)
+ self.assertEqual(result.new_tray_pid, 30)
+ self.assertIn("uv sync 失败", result.message)
+
+
+class VenvHolderTests(unittest.TestCase):
+ def test_only_venv_processes_outside_the_tray_and_this_script_hold_the_venv(self):
+ venv = Path(tempfile.gettempdir()).resolve() / "peach-app" / ".venv"
+ scripts = venv / "Scripts"
+ base = str(Path(tempfile.gettempdir()).resolve() / "python" / "python.exe")
+ paths = {
+ 1: str(scripts / "python.exe"), 2: base, # 本脚本:启动器与解释器
+ 10: str(scripts / "pythonw.exe"), 11: base, # 旧托盘:启动器与解释器
+ 12: str(scripts / "peach.exe"), 13: base, # 旧托盘的子服务
+ 20: str(scripts / "python.exe"), 21: base, # 别人起的调试服务
+ 30: base, # 别的 venv 外进程
+ 40: str(venv.parent / ".venv-other" / "python.exe"),
+ }
+ parents = {2: 1, 1: 11, 11: 10, 10: 5, 12: 11, 13: 12, 21: 20, 20: 6}
+ holders = windows_restart.venv_holders(
+ venv, (11,), own_pid=2, snapshot=lambda: (paths, parents))
+ self.assertEqual(holders, (20,))
+
+
class RestartEntryTests(unittest.TestCase):
+ def setUp(self):
+ # 入口默认读真实账本的任务表与数据根下的启动记录;这里换成空闸门与给定记录。
+ # 入口用 `from … import` 绑定名字,所以补丁打在来源模块上、并且先于 `load_entry()`。
+ self.gate = runtime_prepare.TaskGate()
+ self.startup = None
+ for name, replacement in (
+ ("task_gate", lambda *_args, **_kwargs: self.gate),
+ ("read_record", lambda *_args, **_kwargs: self.startup),
+ ):
+ patcher = mock.patch.object(runtime_prepare, name, side_effect=replacement)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def run_entry(self, argv, result):
+ entry = load_entry()
+ with (
+ mock.patch.object(entry, "find_tray_windows", return_value=()),
+ mock.patch.object(entry, "restart_source_tray", return_value=result) as restart,
+ contextlib.redirect_stdout(io.StringIO()) as printed,
+ ):
+ code = entry.main(argv)
+ return code, json.loads(printed.getvalue()), restart
+
+ def test_tasks_that_cannot_resume_refuse_the_restart(self):
+ blocking = runtime_prepare.ActiveRun(3, "library-processing", "manual", "running", 100, None)
+ self.gate = runtime_prepare.TaskGate(blocking=(blocking,))
+ code, printed, restart = self.run_entry([], windows_restart.RestartResult(True, "ok"))
+ self.assertEqual(code, 1)
+ restart.assert_not_called()
+ self.assertFalse(printed["ok"])
+ self.assertEqual(printed["tasks"]["blocking"][0]["task_key"], "library-processing")
+
+ def test_force_restarts_past_the_gate_and_still_lists_the_tasks(self):
+ blocking = runtime_prepare.ActiveRun(3, "media-repair", "manual", "running", 100, None)
+ self.gate = runtime_prepare.TaskGate(blocking=(blocking,))
+ code, printed, restart = self.run_entry(
+ ["--force"], windows_restart.RestartResult(True, "源码托盘已重启"))
+ self.assertEqual(code, 0)
+ restart.assert_called_once()
+ self.assertIsNotNone(restart.call_args.kwargs["prepare"])
+ self.assertEqual(printed["tasks"]["blocking"][0]["task_key"], "media-repair")
+
+ def test_a_new_tray_whose_startup_preparation_failed_fails_the_restart(self):
+ self.startup = {"pid": 30, "ok": False, "steps": [
+ {"name": "migrations", "state": "failed", "message": "migrate status 失败:locked"}]}
+ code, printed, _restart = self.run_entry(
+ [], windows_restart.RestartResult(True, "源码托盘已重启", new_tray_pid=30))
+ self.assertEqual(code, 1)
+ self.assertFalse(printed["ok"])
+ self.assertIn("locked", printed["message"])
+
+ def test_a_missing_startup_record_is_named_not_assumed(self):
+ code, printed, _restart = self.run_entry(
+ [], windows_restart.RestartResult(True, "源码托盘已重启", new_tray_pid=30))
+ self.assertEqual(code, 0)
+ self.assertIn("未取得新托盘的启动准备记录", printed["message"])
+
def test_the_entry_hands_the_package_to_swap_and_prints_the_outcome(self):
entry = load_entry()
finished = windows_restart.RestartResult(True, "重启完成", backup="C:/dist/backup.exe")
diff --git a/tests/test_runtime_prepare.py b/tests/test_runtime_prepare.py
new file mode 100644
index 000000000..1736bbb42
--- /dev/null
+++ b/tests/test_runtime_prepare.py
@@ -0,0 +1,392 @@
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+from peach import runtime_prepare
+from peach.runtime_prepare import (
+ UV_SYNC, Dependencies, Migrations, RestartPreparation, Step, find_uv, ledger_writer,
+ read_record, record, task_gate,
+)
+from peach.sync import marker_path
+
+
+def completed(returncode: int = 0, stdout: str = "", stderr: str = ""):
+ return subprocess.CompletedProcess([], returncode, stdout, stderr)
+
+
+OUTDATED = (
+ "Would use project environment at: .venv\n"
+ "Would install 1 package\n"
+ " + grpcio==1.84.0\n"
+ "The environment is outdated; run `uv sync` to update the environment\n"
+)
+
+
+class FakeRun:
+ """按调用顺序回放结果,同时记下每次的命令与关键字参数。"""
+
+ def __init__(self, *results):
+ self.results = list(results)
+ self.calls: list[tuple[list[str], dict]] = []
+
+ def __call__(self, command, **kwargs):
+ self.calls.append((list(command), kwargs))
+ result = self.results.pop(0)
+ if isinstance(result, BaseException):
+ raise result
+ return result
+
+
+class ProjectTree:
+ """临时项目根:`uv.lock` 与 `.venv/pyvenv.cfg` 都只是占位文件。"""
+
+ def __init__(self, directory: Path, *, lock: bool = True, venv: bool = True):
+ self.root = directory / "peach-app"
+ self.root.mkdir()
+ if lock:
+ (self.root / "uv.lock").write_text("version = 1\n", encoding="utf-8")
+ if venv:
+ (self.root / ".venv").mkdir()
+ (self.root / ".venv" / "pyvenv.cfg").write_text("home = x\n", encoding="utf-8")
+
+
+class DependencyTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.temp = Path(self.directory.name)
+ self.tree = ProjectTree(self.temp)
+
+ def tearDown(self):
+ self.directory.cleanup()
+
+ def dependencies(self, run, **kwargs):
+ options = {"which": lambda _name: "C:/tools/uv.exe",
+ "environ": {"VIRTUAL_ENV": "C:/elsewhere/.venv", "PATH": ""},
+ "frozen": False, "clock": iter((10.0, 12.5)).__next__}
+ options.update(kwargs)
+ return Dependencies(self.tree.root, run=run, **options)
+
+ def test_a_venv_that_matches_the_lock_is_left_alone(self):
+ run = FakeRun(completed(0, "Would make no changes\n"))
+ step = self.dependencies(run).sync()
+ self.assertEqual(step.state, "current")
+ self.assertEqual(len(run.calls), 1)
+ command, kwargs = run.calls[0]
+ self.assertEqual(command[1:1 + len(UV_SYNC)], list(UV_SYNC))
+ self.assertIn("--check", command)
+ self.assertEqual(command[-2:], ["--project", str(self.tree.root)])
+ # 调用方自己的 venv 不能顶替项目的 `.venv`。
+ self.assertNotIn("VIRTUAL_ENV", kwargs["env"])
+
+ def test_an_outdated_venv_is_synced_without_touching_the_editable_project(self):
+ run = FakeRun(completed(1, OUTDATED), completed(0, "Installed 1 package\n"))
+ step = self.dependencies(run).sync()
+ self.assertEqual(step.state, "synced")
+ self.assertIn("grpcio==1.84.0", step.message)
+ self.assertIn("2.5 秒", step.message)
+ sync_command = run.calls[1][0]
+ self.assertNotIn("--check", sync_command)
+ self.assertIn("--no-install-project", sync_command)
+ self.assertIn("--inexact", sync_command)
+
+ def test_check_alone_reports_stale_and_never_installs(self):
+ run = FakeRun(completed(1, OUTDATED))
+ step = self.dependencies(run).check()
+ self.assertEqual(step.state, "stale")
+ self.assertTrue(step.problem)
+ self.assertEqual(len(run.calls), 1)
+
+ def test_a_failed_sync_is_reported_with_the_tail_of_its_output(self):
+ run = FakeRun(completed(1, OUTDATED),
+ completed(2, "", "error: failed to remove file numpy\\_core.pyd"))
+ step = self.dependencies(run).sync()
+ self.assertTrue(step.failed)
+ self.assertIn("_core.pyd", step.message)
+
+ def test_a_check_that_errors_for_another_reason_is_a_failure_not_stale(self):
+ run = FakeRun(completed(2, "", "error: The lockfile needs to be updated"))
+ step = self.dependencies(run).check()
+ self.assertTrue(step.failed)
+ self.assertIn("lockfile", step.message)
+
+ def test_without_uv_nothing_runs(self):
+ run = FakeRun()
+ step = self.dependencies(run, which=lambda _name: None,
+ environ={"LOCALAPPDATA": str(self.temp)}).sync()
+ self.assertEqual(step.state, "skipped")
+ self.assertIn("未取得 uv", step.message)
+ self.assertEqual(run.calls, [])
+
+ def test_uv_is_found_in_the_winget_package_directory_when_path_lacks_it(self):
+ package = self.temp / "Microsoft" / "WinGet" / "Packages" / "astral-sh.uv_Microsoft.Winget.Source_x"
+ package.mkdir(parents=True)
+ (package / "uv.exe").write_bytes(b"")
+ found = find_uv(which=lambda _name: None, environ={"LOCALAPPDATA": str(self.temp)})
+ self.assertEqual(found, package / "uv.exe")
+
+ def test_frozen_processes_and_trees_without_a_lock_or_venv_skip(self):
+ run = FakeRun()
+ self.assertEqual(self.dependencies(run, frozen=True).check().state, "skipped")
+ (self.temp / "bare").mkdir()
+ bare = ProjectTree(self.temp / "bare", lock=False)
+ self.assertEqual(Dependencies(bare.root, run=run, frozen=False,
+ which=lambda _name: "uv").check().state, "skipped")
+ self.assertEqual(run.calls, [])
+
+
+class WriterTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ root = Path(self.directory.name)
+ self.db = root / "local" / "ledger.db"
+ self.shared = root / "shared" / "ledger.db"
+ self.state = root / "state"
+ for path in (self.db.parent, self.shared.parent, self.state):
+ path.mkdir(parents=True)
+
+ def tearDown(self):
+ self.directory.cleanup()
+
+ def mark(self, db: Path, device: str, generation: int = 1):
+ marker_path(db).write_text(json.dumps({"generation": generation, "device": device}),
+ encoding="utf-8")
+
+ def writer(self, enabled=True):
+ return ledger_writer(replication_enabled=enabled, db=self.db, shared_db=self.shared,
+ state_dir=self.state)
+
+ def test_a_single_machine_is_its_own_writer(self):
+ self.assertTrue(self.writer(enabled=False)[0])
+
+ def test_a_reader_never_counts_as_writer(self):
+ (self.state / "device-id").write_text("mac-1", encoding="utf-8")
+ self.mark(self.shared, "win-1")
+ writer, why = self.writer()
+ self.assertFalse(writer)
+ self.assertIn("win-1", why)
+
+ def test_the_marked_device_is_the_writer(self):
+ (self.state / "device-id").write_text("win-1", encoding="utf-8")
+ self.mark(self.shared, "win-1")
+ self.assertTrue(self.writer()[0])
+
+ def test_no_device_id_means_undecided_and_none_is_written(self):
+ self.mark(self.shared, "win-1")
+ self.assertFalse(self.writer()[0])
+ self.assertFalse((self.state / "device-id").exists())
+
+
+class MigrationTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.db = Path(self.directory.name) / "ledger.db"
+ self.db.write_bytes(b"")
+
+ def tearDown(self):
+ self.directory.cleanup()
+
+ def migrations(self, run, *, writer=(True, "本机是写入端")):
+ return Migrations(self.db, peach=lambda: Path("C:/peach/.venv/Scripts/peach.exe"),
+ writer=lambda: writer, run=run,
+ environ=lambda: {"PEACH_DATA_ROOT": "C:/peach-data"})
+
+ def test_a_reader_never_migrates(self):
+ run = FakeRun()
+ step = self.migrations(run, writer=(False, "写入端是 win-1,本机是只读端")).apply()
+ self.assertEqual(step.state, "skipped")
+ self.assertIn("只读端", step.message)
+ self.assertEqual(run.calls, [])
+
+ def test_a_missing_ledger_is_skipped(self):
+ self.db.unlink()
+ run = FakeRun()
+ self.assertEqual(self.migrations(run).apply().state, "skipped")
+ self.assertEqual(run.calls, [])
+
+ def test_nothing_pending_runs_only_the_status(self):
+ run = FakeRun(completed(0, f"database: {self.db}\nmigrations: 43, pending: 0\n"))
+ step = self.migrations(run).apply()
+ self.assertEqual(step.state, "current")
+ self.assertEqual(len(run.calls), 1)
+ command, kwargs = run.calls[0]
+ self.assertEqual(command[1:], ["migrate", "status", "--db", str(self.db)])
+ self.assertEqual(kwargs["env"]["PYTHONIOENCODING"], "utf-8")
+ self.assertEqual(kwargs["env"]["PEACH_DATA_ROOT"], "C:/peach-data")
+
+ def test_pending_migrations_are_applied_with_the_backup_reported(self):
+ backup = self.db.with_name("ledger.pre-migrate-20261002-101500.db")
+ run = FakeRun(
+ completed(0, "migrations: 43, pending: 2\nPENDING 0042 want\nPENDING 0043 x\n"),
+ completed(0, f"database: {self.db}\nbackup: {backup}\napplied: 0042, 0043\n"),
+ )
+ step = self.migrations(run).apply()
+ self.assertEqual(step.state, "applied")
+ self.assertIn("0042, 0043", step.message)
+ self.assertIn(str(backup), step.message)
+ self.assertEqual(run.calls[1][0][1:],
+ ["migrate", "upgrade", "--yes", "--db", str(self.db)])
+
+ def test_a_failed_upgrade_is_reported_not_swallowed(self):
+ run = FakeRun(completed(0, "migrations: 43, pending: 1\n"),
+ completed(1, "", "sqlite3.OperationalError: database is locked"))
+ step = self.migrations(run).apply()
+ self.assertTrue(step.failed)
+ self.assertIn("database is locked", step.message)
+ self.assertIn("备份", step.message)
+
+ def test_a_status_that_cannot_run_is_a_failure(self):
+ step = self.migrations(FakeRun(OSError("peach.exe missing"))).apply()
+ self.assertTrue(step.failed)
+ self.assertIn("peach.exe missing", step.message)
+
+
+class RecordTests(unittest.TestCase):
+ def test_the_record_is_read_back_only_for_the_tray_that_wrote_it(self):
+ with tempfile.TemporaryDirectory() as directory:
+ state = Path(directory) / "state"
+ written = record(state, [Step("migrations", "applied", "已执行迁移 0042"),
+ Step("readiness", "current", "服务已就绪")], pid=4242)
+ self.assertTrue(written["ok"])
+ self.assertEqual(read_record(state, pid=4242)["steps"][0]["state"], "applied")
+ self.assertIsNone(read_record(state, pid=1))
+
+ def test_stale_dependencies_make_the_record_not_ok(self):
+ with tempfile.TemporaryDirectory() as directory:
+ written = record(Path(directory), [Step("dependencies", "stale", "不一致")], pid=1)
+ self.assertFalse(written["ok"])
+
+
+class TaskGateTests(unittest.TestCase):
+ HOST = "peach-win"
+
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.db = Path(self.directory.name) / "ledger.db"
+ with sqlite3.connect(self.db) as connection:
+ connection.execute(
+ "CREATE TABLE task_run(id INTEGER PRIMARY KEY, task_key TEXT, trigger TEXT, "
+ "status TEXT, pid INTEGER, host TEXT, followup_key TEXT)")
+ connection.executemany(
+ "INSERT INTO task_run(id, task_key, trigger, status, pid, host, followup_key) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ [
+ (1, "entity-avatar", "manual", "pending", None, self.HOST, "avatar:7"),
+ (2, "follow-check", "scheduled", "running", 100, self.HOST, None),
+ (3, "library-processing", "manual", "running", 100, self.HOST, None),
+ (4, "scrape-codes", "cli", "running", 200, self.HOST, None),
+ (5, "media-repair", "manual", "running", 300, "peach-mac", None),
+ (6, "taste-refresh", "manual", "succeeded", 100, self.HOST, None),
+ ])
+ connection.close()
+
+ def tearDown(self):
+ self.directory.cleanup()
+
+ def test_runs_are_split_into_resumable_blocking_and_stale(self):
+ gate = task_gate(self.db, host=self.HOST, alive=lambda pid: pid == 100)
+ self.assertEqual([run.id for run in gate.resumable], [1, 2])
+ self.assertEqual([run.id for run in gate.blocking], [3])
+ # CLI 那条的进程已经不在:重启伤不到它,不该拦。
+ self.assertEqual([run.id for run in gate.stale], [4])
+ self.assertTrue(gate.refused)
+ self.assertIn("library-processing", gate.refusal())
+ self.assertIn("--force", gate.refusal())
+
+ def test_a_live_cli_run_blocks_too(self):
+ gate = task_gate(self.db, host=self.HOST, alive=lambda _pid: True)
+ self.assertEqual([run.task_key for run in gate.blocking],
+ ["library-processing", "scrape-codes"])
+
+ def test_only_resumable_work_lets_the_restart_through(self):
+ with sqlite3.connect(self.db) as connection:
+ connection.execute("DELETE FROM task_run WHERE id IN (3, 4)")
+ connection.close()
+ gate = task_gate(self.db, host=self.HOST, alive=lambda _pid: True)
+ self.assertFalse(gate.refused)
+ self.assertEqual(len(gate.as_dict()["resumable"]), 2)
+
+ def test_a_ledger_without_the_table_or_without_a_file_does_not_block(self):
+ self.assertFalse(task_gate(self.db.with_name("none.db"), host=self.HOST,
+ alive=lambda _pid: True).refused)
+ empty = self.db.with_name("empty.db")
+ sqlite3.connect(empty).close()
+ gate = task_gate(empty, host=self.HOST, alive=lambda _pid: True)
+ self.assertFalse(gate.refused)
+ self.assertIn("task_run", gate.note)
+
+
+class FakeDependencies:
+ def __init__(self, checked: Step, synced: Step | None = None):
+ self.checked, self.synced_step = checked, synced
+ self.synced = 0
+
+ def check(self):
+ return self.checked
+
+ def sync(self):
+ self.synced += 1
+ return self.synced_step
+
+
+class RestartPreparationTests(unittest.TestCase):
+ STALE = Step("dependencies", "stale", "项目 venv 与 uv.lock 不一致,要装 1 个包:grpcio==1.84.0")
+
+ def test_a_current_venv_neither_refuses_nor_syncs(self):
+ dependencies = FakeDependencies(Step("dependencies", "current", "一致"))
+ holders = []
+ preparation = RestartPreparation(dependencies, holders=lambda pid: holders.append(pid) or ())
+ self.assertIsNone(preparation.before_stop(10))
+ self.assertEqual(preparation.while_stopped(), (True, "一致"))
+ self.assertEqual(dependencies.synced, 0)
+ self.assertEqual(holders, [])
+
+ def test_other_venv_users_refuse_the_restart_before_anything_stops(self):
+ asked = []
+ preparation = RestartPreparation(FakeDependencies(self.STALE),
+ holders=lambda pid: asked.append(pid) or (48420,))
+ refusal = preparation.before_stop(10)
+ self.assertIn("48420", refusal)
+ self.assertEqual(asked, [10])
+
+ def test_a_stale_venv_is_synced_while_the_tray_is_stopped(self):
+ dependencies = FakeDependencies(self.STALE, Step("dependencies", "synced", "已同步"))
+ preparation = RestartPreparation(dependencies, holders=lambda _pid: ())
+ self.assertIsNone(preparation.before_stop(10))
+ self.assertEqual(dependencies.synced, 0)
+ self.assertEqual(preparation.while_stopped(), (True, "已同步"))
+ self.assertEqual(dependencies.synced, 1)
+
+ def test_a_failed_sync_is_reported_as_not_ready(self):
+ dependencies = FakeDependencies(self.STALE, Step("dependencies", "failed", "uv sync 失败"))
+ preparation = RestartPreparation(dependencies, holders=lambda _pid: ())
+ preparation.before_stop(10)
+ self.assertEqual(preparation.while_stopped(), (False, "uv sync 失败"))
+
+
+class ImportBoundaryTests(unittest.TestCase):
+ def test_the_restart_path_loads_no_third_party_module(self):
+ """重启脚本要在活着时替换 venv 里的包,被加载的 `.pyd` 在 Windows 上换不掉。"""
+ probe = (
+ "import sys; import peach.runtime_prepare, peach.windows_restart, peach.jobs, "
+ "peach.config\n"
+ "names = sorted(name for name, module in sys.modules.items()\n"
+ " if 'site-packages' in (getattr(module, '__file__', '') or '')\n"
+ " and not name.startswith(('_distutils_hack', '_virtualenv')))\n"
+ "print(','.join(names))"
+ )
+ source_root = str(Path(runtime_prepare.__file__).parents[1])
+ output = subprocess.run([sys.executable, "-X", "utf8", "-c", probe], check=True,
+ capture_output=True, text=True, encoding="utf-8",
+ env={**os.environ, "PYTHONPATH": source_root})
+ self.assertEqual(output.stdout.strip(), "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_tray.py b/tests/test_tray.py
index df32d5635..30e3f5910 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -2,10 +2,12 @@ import contextlib
import importlib.util
import inspect
import io
+import json
import logging
import os
import plistlib
import re
+import subprocess
import sys
import tempfile
import threading
@@ -25,7 +27,7 @@ def load_script(name: str):
return module
-from peach import appid, onboarding, settings_file
+from peach import appid, onboarding, runtime_prepare, settings_file
from peach import tray as tray_module
from peach.config import SECRETS_DIR
from peach.tray import (
@@ -1340,5 +1342,217 @@ class TrayLogFileTests(unittest.TestCase):
self.assertIn("拉起 http 服务", text)
+class ReadyResponse:
+ def __init__(self, status_code, payload):
+ self.status_code, self.payload = status_code, payload
+
+ def json(self):
+ return self.payload
+
+
+class FakeStep:
+ """给出固定结果的依赖核对或迁移,顺手记下被调用的时刻。"""
+
+ def __init__(self, events, label, step):
+ self.events, self.label, self.step = events, label, step
+
+ def check(self):
+ self.events.append(self.label)
+ return self.step
+
+ apply = check
+
+
+class TrayPreparationTests(unittest.TestCase):
+ """依赖、迁移与就绪检查在托盘里的落点(ADR-0091)。"""
+
+ CURRENT = runtime_prepare.Step("dependencies", "current", "项目 venv 与 uv.lock 一致")
+ STALE = runtime_prepare.Step("dependencies", "stale",
+ "项目 venv 与 uv.lock 不一致,要装 1 个包:grpcio==1.84.0")
+ APPLIED = runtime_prepare.Step("migrations", "applied", "已执行迁移 0042,迁移前备份 x.db")
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp.name)
+ self.events: list = []
+ self.spawned: list = []
+
+ def tearDown(self):
+ self.temp.cleanup()
+
+ def preparation(self, dependencies=CURRENT, migration=APPLIED, process=None):
+ def spawn():
+ self.spawned.append(True)
+ if process is None:
+ raise OSError("python.exe missing")
+ return process
+
+ return tray_module.TrayPreparation(
+ dependencies=FakeStep(self.events, "deps", dependencies),
+ migrations=FakeStep(self.events, "migrate", migration),
+ state_dir=self.root / "state",
+ restart_log=self.root / "logs" / "tray-restart.out.log",
+ spawn_restart=spawn,
+ )
+
+ def manager(self, *, ready=True, problems=()):
+ manager = Mock()
+ manager.specs = ()
+ manager.start_missing.side_effect = lambda: self.events.append("start")
+ manager.wait_until_ready.return_value = ready
+ manager.readiness_problems.return_value = list(problems)
+
+ def restart(prepare=None):
+ self.events.append("stop")
+ if prepare is not None:
+ prepare()
+ self.events.append("start")
+ return ready
+
+ manager.restart.side_effect = restart
+ return manager
+
+ def tray(self, manager, preparation):
+ gate = Mock()
+ gate.waiting = False
+ snapshot = VersionSnapshot("0.37.0", "master", "abc12345", False, True, "origin/master")
+ updates = FakeUpdates()
+ updates.sweep_artifacts = lambda: None
+ with patch("peach.tray.pystray.Icon", return_value=Mock()):
+ return PeachTray(manager, FakeVersions(snapshot), updates, gate,
+ preparation=preparation)
+
+ def run_tray(self, tray):
+ with (
+ patch("peach.tray.ledger_backups.prune"),
+ patch("peach.tray.sweep_onefile_extractions"),
+ patch.object(tray, "_monitor"),
+ ):
+ tray.run()
+
+ def press_restart(self, tray):
+ icon = Mock()
+ tray.restart(icon)
+ self.assertTrue(tray._action_lock.acquire(timeout=5))
+ tray._action_lock.release()
+ return icon
+
+ def test_startup_migrates_before_the_first_service_starts(self):
+ tray = self.tray(self.manager(), self.preparation())
+ self.run_tray(tray)
+ self.assertEqual(self.events[:3], ["deps", "migrate", "start"])
+ recorded = runtime_prepare.read_record(self.root / "state", pid=os.getpid())
+ self.assertTrue(recorded["ok"])
+ self.assertEqual([step["name"] for step in recorded["steps"]],
+ ["dependencies", "migrations", "readiness"])
+ self.assertIsNone(tray._startup_warning)
+
+ def test_startup_reports_a_failed_migration_and_an_unready_schema(self):
+ failed = runtime_prepare.Step("migrations", "failed", "migrate status 失败:database is locked")
+ manager = self.manager(problems=["HTTPS 未就绪:账本结构与迁移不一致"])
+ tray = self.tray(manager, self.preparation(migration=failed))
+ self.run_tray(tray)
+ self.assertIn("database is locked", tray._startup_warning)
+ self.assertIn("账本结构与迁移不一致", tray._startup_warning)
+ self.assertFalse(runtime_prepare.read_record(self.root / "state", pid=os.getpid())["ok"])
+
+ def test_restart_migrates_while_the_services_are_stopped(self):
+ tray = self.tray(self.manager(), self.preparation())
+ icon = self.press_restart(tray)
+ self.assertEqual(self.events, ["deps", "stop", "migrate", "start"])
+ self.assertEqual(self.spawned, [])
+ icon.notify.assert_not_called()
+
+ def test_stale_dependencies_hand_the_restart_to_a_whole_tray_restart(self):
+ process = Mock()
+ process.wait.side_effect = subprocess.TimeoutExpired("restart", 1)
+ manager = self.manager()
+ tray = self.tray(manager, self.preparation(dependencies=self.STALE, process=process))
+ icon = self.press_restart(tray)
+ self.assertEqual(self.spawned, [True])
+ manager.restart.assert_not_called()
+ self.assertIn("整体重启托盘", icon.notify.call_args_list[0].args[0])
+
+ def test_a_refused_whole_tray_restart_falls_back_to_the_services(self):
+ log = self.root / "logs" / "tray-restart.out.log"
+ log.parent.mkdir(parents=True)
+ log.write_text(json.dumps({"ok": False, "message": "拒绝重启:PID 48420 还在用项目 venv"},
+ ensure_ascii=False) + "\n", encoding="utf-8")
+ process = Mock()
+ process.wait.return_value = 1
+ manager = self.manager()
+ tray = self.tray(manager, self.preparation(dependencies=self.STALE, process=process))
+ icon = self.press_restart(tray)
+ manager.restart.assert_called_once()
+ messages = " ".join(call.args[0] for call in icon.notify.call_args_list)
+ self.assertIn("48420", messages)
+ # 依赖仍不一致,重启子服务之后也要再说一遍。
+ self.assertIn("grpcio", icon.notify.call_args_list[-1].args[0])
+
+ def test_without_a_preparation_the_tray_only_restarts_services(self):
+ manager = self.manager()
+ tray = self.tray(manager, None)
+ self.press_restart(tray)
+ self.assertEqual(self.events, ["stop", "start"])
+ manager.readiness_problems.assert_not_called()
+
+ def test_service_restart_runs_the_preparation_between_stop_and_start(self):
+ order = []
+ process = Mock()
+ process.poll.return_value = None
+ process.terminate.side_effect = lambda: order.append("stop")
+ process.wait.return_value = 0
+ spec = ServiceSpec("https", "https://local/healthz", ("peach", "serve"), True)
+ manager = ServiceManager((spec,), popen=lambda *_a, **_k: order.append("start") or process,
+ log_dir=self.root / "logs",
+ health_get=Mock(side_effect=OSError("down")))
+ with patch("peach.tray.assign_to_job"), patch("peach.tray.create_kill_on_close_job"):
+ manager.start_missing()
+ order.clear()
+ with patch.object(manager, "wait_until_ready", return_value=True):
+ manager.restart(prepare=lambda: order.append("prepare"))
+ self.assertEqual(order, ["stop", "prepare", "start"])
+
+ def test_readiness_is_read_from_the_api_service_only(self):
+ asked = []
+
+ def get(url, **kwargs):
+ asked.append((url, kwargs["verify"]))
+ if url.startswith("http://"):
+ return ReadyResponse(200, {"ok": True, "service": "peach-redirect"})
+ return ReadyResponse(503, {"ready": False, "checks": {
+ "configured": True, "web": True, "database": True, "schema": False}})
+
+ specs = (ServiceSpec("http", "http://127.0.0.1/healthz", ("peach",), True),
+ ServiceSpec("https", "https://10.0.0.2/healthz", ("peach",), "ca.crt"))
+ manager = ServiceManager(specs, health_get=get, log_dir=self.root)
+ self.assertEqual(manager.readiness_problems(), ["HTTPS 未就绪:账本结构与迁移不一致"])
+ self.assertEqual(asked, [("http://127.0.0.1/healthz?ready=1", True),
+ ("https://10.0.0.2/healthz?ready=1", "ca.crt")])
+
+ def test_the_whole_tray_restart_is_detached_and_logged(self):
+ python = self.root / ".venv" / tray_module._BIN_DIR / (
+ "python.exe" if os.name == "nt" else "python")
+ script = self.root / "scripts" / "restart_windows_tray.py"
+ log = self.root / "logs" / "tray-restart.out.log"
+ with self.assertRaises(FileNotFoundError):
+ tray_module.spawn_tray_restart(log, popen=Mock(), root=self.root)
+ for path in (python, script):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"")
+ seen = {}
+
+ def popen(argv, **kwargs):
+ seen.update(argv=argv, **kwargs)
+ return Mock()
+
+ tray_module.spawn_tray_restart(log, popen=popen, root=self.root)
+ self.assertEqual(seen["argv"][-3:], [str(script), "--source", "--force"])
+ self.assertEqual(seen["env"]["PYTHONIOENCODING"], "utf-8")
+ self.assertTrue(seen["stdout"].closed)
+ if os.name == "nt":
+ self.assertTrue(seen["creationflags"] & subprocess.DETACHED_PROCESS)
+
+
if __name__ == "__main__":
unittest.main()