Skip to content

armgit / peach

Public Imported from GitHub
0

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

perf(config): 开机启动项状态按快捷方式指纹留存并在服务起来时预热

longmeidao5b21899b86bd
diff --git a/src/peach/api.py b/src/peach/api.py
index 8020f6dc5..c7e37f02b 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -174,6 +174,22 @@ def create_app(
available=managed_configuration() and bool(settings.configured),
)
+ async def warm_startup_entries():
+ """配置页首屏要的开机启动项状态,先在后台问一遍。
+
+ 那一格是 `/api/configuration` 同步路径上唯一一件慢事:读一个 `.lnk` 得起一个
+ `powershell.exe`,本机三个快捷方式加起来 2.5 秒,而它正好挡在用户点开设置之后。
+ 这里先问一次,`desktop_startup` 按 `.lnk` 的指纹留着结论,等用户真点开时是现成的。
+ """
+ if not (managed_configuration() and settings.configured):
+ return
+ from . import desktop_startup
+ try:
+ await asyncio.to_thread(desktop_startup.snapshot)
+ except Exception:
+ # 预热失败不该影响服务起不起得来,配置页照旧自己现问一遍。
+ logging.getLogger(__name__).debug("startup entry warmup failed", exc_info=True)
+
@asynccontextmanager
async def lifespan(_app: FastAPI):
# 上一次服务是被强杀的话,表里会留下几行永远停在 `running` 的记录,它们还占着
@@ -185,6 +201,7 @@ def create_app(
"task center recovered %s interrupted run(s)", len(recovered))
follow_scheduler.start()
automatic_updates.start()
+ warmup = asyncio.create_task(warm_startup_entries())
if mdns is not None:
try:
await asyncio.to_thread(mdns.start)
@@ -194,6 +211,7 @@ def create_app(
try:
yield
finally:
+ warmup.cancel()
follow_scheduler.stop()
automatic_updates.stop()
# 死链检查和资源对账的后台线程是 daemon,本来挡不住进程退出;这里显式收
diff --git a/src/peach/desktop_startup.py b/src/peach/desktop_startup.py
index f4e5290cc..50501f8e0 100644
--- a/src/peach/desktop_startup.py
+++ b/src/peach/desktop_startup.py
@@ -62,7 +62,36 @@ try {
"""
+#: 读到的快捷方式状态,键是路径,值是 `(指纹, 结论)`。指纹见 `_fingerprint`。
+_READ_CACHE: dict[str, tuple[tuple, dict]] = {}
+
+
+def _fingerprint(path: Path) -> tuple:
+ """这个 `.lnk` 的当前身份。文件不在就是 `()`,内容变了指纹一定跟着变。"""
+ try:
+ stat = path.stat()
+ except OSError:
+ return ()
+ return (stat.st_mtime_ns, stat.st_size)
+
+
def shortcut(action: str, path: Path, *, target: str = "", arguments: str = "", directory: str = "", expected: str = "") -> dict:
+ """对一个 `.lnk` 读、写或删,结论由 PowerShell 的一行 JSON 给出。
+
+ 读是配置页首屏的同步路径上唯一一件慢事:起一个 `powershell.exe` 要 0.8–1.7 秒,而
+ 这一页最多读三个快捷方式。所以读走两道近路,写和删一律照直执行——它们要落盘。
+
+ 文件不在就不起进程:脚本对 `read` 的这一支本来也只回一句「没有」。剩下真存在的那几个
+ 按 `(mtime, size)` 记住结论,`.lnk` 一被改写指纹就变,缓存自然作废。
+ """
+ mark = ()
+ if action == "read":
+ mark = _fingerprint(path)
+ if not mark:
+ return {"ok": True, "enabled": False, "target": "", "arguments": ""}
+ hit = _READ_CACHE.get(str(path))
+ if hit and hit[0] == mark:
+ return hit[1]
encoded = base64.b64encode(_SHORTCUT_SCRIPT.encode("utf-16-le")).decode("ascii")
# 和 folder_picker 相同:发行包使用 Windows 自带的 PowerShell,不要求用户安装 pwsh。
shell = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32/WindowsPowerShell/v1.0/powershell.exe"
@@ -81,6 +110,13 @@ def shortcut(action: str, path: Path, *, target: str = "", arguments: str = "",
# 校验不通过在消息里长得一模一样,谁都没法往下查。
raise OSError("启动项未能保存,请检查当前用户的启动文件夹权限"
f"(PowerShell:{_shortcut_reason(payload, result)})")
+ if action == "read":
+ # 记的是读之前那次指纹。这一趟里文件正好被换掉的话,它与之后 stat 出来的对不上,
+ # 下次就重读一遍;记读完那次则相反——旧结论会配上新指纹,从此一直命中错的。
+ _READ_CACHE[str(path)] = (mark, payload)
+ else:
+ # 写和删都改了这个路径上的东西,旧结论当场作废,不等下次 stat 去发现。
+ _READ_CACHE.pop(str(path), None)
return payload
diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.py
index 80c14dee8..a7e335be4 100644
--- a/tests/test_desktop_settings.py
+++ b/tests/test_desktop_settings.py
@@ -57,6 +57,9 @@ class DesktopSettingsTests(unittest.TestCase):
(self.program / 'Peach.exe').touch()
self.config = SimpleNamespace(data_root=self.data, path=self.data / 'config.toml', locations={'local': (str(self.root / 'media'),)}, mounts={},
directory=lambda key: self.data / key)
+ # 读到的快捷方式状态是模块级的,跨用例留着会让「起了几个进程」数不准。
+ desktop_startup._READ_CACHE.clear()
+ self.addCleanup(desktop_startup._READ_CACHE.clear)
def test_uninstall_plan_keeps_media_and_can_preserve_all_data(self):
keep = desktop_uninstall.plan(self.config, delete_data=False, program=self.program)
@@ -246,6 +249,60 @@ class DesktopSettingsTests(unittest.TestCase):
self.skipTest(f'系统 ANSI 码页 cp{codepage} 表示不了「{name}」,WScript.Shell 存不下')
self._shortcut_round_trip(name)
+ def test_the_startup_entry_state_is_warmed_up_before_anyone_opens_settings(self):
+ """服务起来时后台先问一遍启动项,别把那 2.5 秒留给点开设置的那一下。
+
+ 条件跟 `configurable` 的前两条对齐:不是托盘管的、或还没过首次配置,这一格本来
+ 就出不来,没有值得预热的东西,起一个 `powershell.exe` 只是白耗。预热失败也不许
+ 影响服务起不起得来——配置页自己现问一遍就是了。
+ """
+ api = (Path(__file__).resolve().parents[1] / 'src/peach/api.py').read_text(encoding='utf-8')
+ self.assertIn('if not (managed_configuration() and settings.configured):\n return', api)
+ self.assertIn('await asyncio.to_thread(desktop_startup.snapshot)', api)
+ self.assertIn('warmup = asyncio.create_task(warm_startup_entries())', api)
+ self.assertIn('warmup.cancel()', api)
+ # 起服务这一步不等它:预热要是同步跑,省下的那 2.5 秒只是挪到了开机时。
+ self.assertNotIn('await warm_startup_entries()', api)
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 原生快捷方式')
+ def test_reading_shortcuts_spends_a_powershell_process_only_when_it_has_to(self):
+ """读 `.lnk` 是配置页首屏唯一一件慢事,两道近路都要成立。
+
+ 起一个 `powershell.exe` 要 0.8–1.7 秒,配置页那一格最多读三个快捷方式,加起来
+ 2.5 秒,正好挡在用户点开设置之后。所以文件不在就不起进程(脚本对这一支本来也
+ 只回一句「没有」),真存在的按 `(mtime, size)` 记住结论。
+
+ 指纹一变必须重读:快捷方式被改写之后还报旧的目标,配置页上那个开关就会一直
+ 显示成用户没设过的那一档。
+ """
+ program = str(self.program / 'Peach.exe')
+ path = self.root / 'cached fixture.lnk'
+ calls = []
+ real = subprocess.run
+
+ def counted(*args, **kwargs):
+ calls.append(args[0])
+ return real(*args, **kwargs)
+
+ with patch.object(desktop_startup.subprocess, 'run', counted):
+ missing = desktop_startup.shortcut('read', self.root / '从来没有过.lnk')
+ self.assertEqual(missing, {'ok': True, 'enabled': False, 'target': '', 'arguments': ''})
+ self.assertEqual(calls, [])
+ desktop_startup.shortcut('write', path, target=program, arguments='--silent',
+ directory=str(self.program))
+ written = len(calls)
+ first = desktop_startup.shortcut('read', path)
+ self.assertEqual(len(calls), written + 1)
+ self.assertEqual(desktop_startup.shortcut('read', path), first)
+ self.assertEqual(len(calls), written + 1, '同一个快捷方式读第二遍不该再起一个进程')
+ other = self.program / 'Other.exe'
+ other.touch()
+ desktop_startup.shortcut('write', path, target=str(other), arguments='--show',
+ directory=str(self.program), expected=first['target'])
+ again = desktop_startup.shortcut('read', path)
+ self.assertEqual(Path(again['target']).resolve(), other.resolve())
+ self.assertEqual(again['arguments'], '--show')
+
@unittest.skipUnless(os.name == 'nt', 'Windows 原生快捷方式')
def test_a_failed_shortcut_call_reports_what_powershell_said(self):
"""失败的消息带上脚本自报的原因、异常类型和行号,不只给一句「请检查权限」。