Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(runtime): 安装时暂停采集并在完成后自动续跑

longmeidaod901bbe047c2
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1a411c675..510910612 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -78,6 +78,7 @@ jobs:
Compress-Archive -Path dist/Peach -DestinationPath 'release/Peach-${{ steps.version.outputs.version }}-windows-x64.zip'
Copy-Item 'dist/Peach-${{ steps.version.outputs.version }}-windows-x64-setup.exe' release/
Copy-Item scripts/smoke_desktop.py release/smoke_desktop.py
+ Copy-Item scripts/smoke_update_tasks.py release/smoke_update_tasks.py
python scripts/changelog.py --notes '${{ steps.version.outputs.version }}' --to release/RELEASE_NOTES.md
if ($LASTEXITCODE -ne 0) { throw 'CHANGELOG.md 缺这一版的一节,不发没有说明的版本' }
- uses: actions/upload-artifact@v7
@@ -120,6 +121,11 @@ jobs:
while ((Test-Path -LiteralPath $Installed) -and (Get-Date) -lt $Deadline) { Start-Sleep -Seconds 1 }
if (Test-Path -LiteralPath $Installed) { throw '卸载后程序目录仍在' }
if ((Test-Path -LiteralPath $Key) -or (Test-Path -LiteralPath $Menu)) { throw '卸载后仍留有登记项或开始菜单项' }
+ - name: 验证在途任务保护与覆盖安装后的恢复
+ shell: pwsh
+ run: |
+ python smoke_update_tasks.py candidate/Peach/Peach.exe --installer './Peach-${{ needs.windows.outputs.version }}-windows-x64-setup.exe'
+ if ($LASTEXITCODE -ne 0) { throw '任务保护与恢复验收失败' }
- name: 保留制品验收失败日志
if: failure()
uses: actions/upload-artifact@v7
diff --git a/README.md b/README.md
index 84973ece8..40bbc3874 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,8 @@ https://github.com/user-attachments/assets/a5610874-e611-41bb-be22-7d99f0d64b62
Windows 独立包可在配置页「应用与维护」检查并下载更新;下载完成后确认重启安装。自动检查与下载默认关闭,可在同一处开启。
+下载更新不会停止任务。应用内重启安装和安装包覆盖安装会保存采集进度、暂停刮削与抽帧,安装完成后自动继续;安装期间发起的采集任务会等待安装完成。取消安装或服务意外退出后,未完成的馆藏资料、本地预览、时间轴缩略图和封面任务也会自动恢复,复用已完成结果;主动关闭缩略图采集则不恢复。
+
测试包还没有代码签名。Windows 提示「已保护你的电脑」时,确认文件来自本项目的 Release,再点「更多信息 → 仍要运行」。转码和缩略图要用到 FFmpeg,没装也能浏览和播放 MP4、WebM,安装方法见 [Windows 测试版](docs/TESTING_DESKTOP.md)。
Windows 托盘独立运行,关闭启动它的 Codex、Claude 或终端不会退出 Peach。托盘异常退出后会自动尝试恢复;5 分钟内最多恢复 3 次。主动选择「退出 Peach」会保持关闭。退出原因和恢复结果可在日志目录的 `tray-lifecycle.log` 中查看。
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 9c3cda15c..863100717 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -363,7 +363,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt
- 构建入口是 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 生成方形 Logo 与多尺寸 `.ico`,再构建单一的 `dist/Peach/Peach.exe`。不带参数运行是托盘,`serve`/`migrate` 运行 CLI。
- 对外测试包由 `.github/workflows/release.yml` 构建:`build_windows.ps1 -Standalone` 用 PyInstaller onedir 生成完整的 Windows 程序目录,压缩后由不检出源码的消费任务运行 `scripts/smoke_desktop.py`。冒烟测试会完成首次设置、以 `0.0.0.0` 重启、从本机局域网地址读 `/healthz`、确认 mDNS 已装配,并用访问密码登录。`v<__version__>` 标签与版本不一致会失败;制品验收通过后才创建 GitHub 预发布并附 SHA256。`workflow_dispatch` 只生成和验收制品。
-- 安装包由 `build_windows.ps1 -Installer` 在同一个程序目录上调 Inno Setup 6 的 `ISCC` 编译 `scripts/installer/peach.iss`,产物是 `dist/Peach-<版本>-windows-x64-setup.exe`;找 `ISCC` 的顺序是 `PEACH_ISCC`、`PATH`、两个默认安装位置。它只装到当前用户的 `%LOCALAPPDATA%\Programs\Peach`,程序目录不可选:自更新要在程序目录旁建事务目录,数据根又在 `%LOCALAPPDATA%\Peach` 下,可选目录会让两者重叠。覆盖安装与卸载前分别调 `Peach.exe --installer-stop`、`--installer-uninstall` 停托盘(后者再撤启动项与桌面图标),覆盖安装后账本存在就跑 `migrate upgrade --yes`;这些约定与 `AppId` 在 `src/peach/desktop_installer.py`。消费任务静默安装、对安装位置跑同一个冒烟,再静默卸载并确认程序目录、卸载登记项与开始菜单项都已移除。
+- 安装包由 `build_windows.ps1 -Installer` 在同一个程序目录上调 Inno Setup 6 的 `ISCC` 编译 `scripts/installer/peach.iss`,产物是 `dist/Peach-<版本>-windows-x64-setup.exe`;找 `ISCC` 的顺序是 `PEACH_ISCC`、`PATH`、两个默认安装位置。默认安装到当前用户的 `%LOCALAPPDATA%\Programs\Peach`,可选择独立、可写且不与数据目录重叠的程序目录。覆盖安装前由随包临时运行时执行 `--installer-prepare`,通知采集任务保存进度并暂停,随后停止托盘,覆盖程序并迁移实际数据目录中的已有账本,最后释放安装保护。安装期间的新采集请求进入等待;安装完成后恢复,取消时原服务也会续跑。卸载走 `--installer-uninstall`,撤销启动项与桌面图标并保留数据。约定与 `AppId` 在 `src/peach/desktop_installer.py`。
- 独立包构建会把固定版本的官方 `cloudflared-windows-amd64.exe` 放在 `Peach.exe` 旁边,并用 `scripts/cloudflared-windows.json` 里的 SHA-256 校验。构建前运行 `scripts/fetch_cloudflared.ps1`,或给 `build_windows.ps1 -CloudflaredPath` 一个哈希相同的文件。源码运行不携带这个二进制。
- 每个包都带构建身份:`build_windows.ps1` 在调用 PyInstaller 前把 `{commit, version, built_at}` 写进 `build/windows/build-info.json`,再用 `--add-data` 放到包根,本机托盘与独立测试包共用。构建机没有 git 或源码不是检出时 `commit` 为 `null`,构建照常。`peach.buildinfo.frozen_build()` 只在 `sys.frozen` 时读它;文件缺失或格式不对返回 `None`,托盘照常启动,只是认为自己身份未取得。
- PyInstaller 的资源直接在 `sys._MEIPASS` 下,没有源码树的 `src/` 这一层;打包后的 `migrate`、Web 与品牌资源都要从这里解析,不能在 `config.py` 里固定取 `parents[2]`。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 152d41807..73653efc9 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -164,7 +164,7 @@ OneJAV、Free JAV Torrent 只给种子链接。这类条目经索引器同源的
- React 设置分区用 `frontend/src/react/settings/section.tsx`:`Section` 给标题、卡片与表单外壳,`Footer`、`Note`、`ErrorText`、`FactList`、`Progress`、`Disclosure` 补齐 BoardUI 注册表没有的部分。`service-preferences.tsx` 组合缩略图与订阅采集参数,继续使用已有设置、关注计划和缩略图 API。`use-action.ts` 的 `useAction` 管提交互斥、卸载取消与原位错误,`busy-props.ts` 的 `busyProps` 写忙态;媒体文件夹行(`folder-rows.tsx`)与密码加确认两格(`password-pair.tsx`)由配置页与首启页共用;密码校验与服务端回执归各分区,不自动重试写入。口味读取、封面采集、amane 桥重建、关注检查与查找共用 `frontend/src/react/background-job.ts` 的 `useBackgroundJob`。
- 增量列表用 `catalog-grid/catalog-grid-page.tsx` 的 `LoadMore`:请求互斥、失败留原位重试、卸载即停;目录、资料页照片墙与关注页注入读取和可用条件。首页页码在读取成功后推进,照片沿用随机种子,关注合并分组;显式页码用 `pagination.ts`。
- 在图上框一块由 `frontend/src/crop-geometry.ts`(纯算术)加 `react/crop/crop-frame.tsx`(四块压暗、一个可拖可缩的框)承担,换头像与裁封面共用;坐标一律是源图像素、右下开区间。不引 `react-image-crop`:换到的只有把手样式,代价是一条依赖和它自己的坐标约定。裁封面通过 Application 的媒体域动作连接 React 裁剪组件(ADR-0031)。
-- 后台任务用 `watchJob`、`followJobProgress` 默认面板与 `jobActivityHtml` 的真实计数/未知总量显示,关注、来源扫描、链接检查和扫描采集共用;业务保留启动、终态回执和结果面板,不新增轮询循环。任务本体是 `jobs.BackgroundJob`,不加队列或调度依赖;状态在服务进程,浏览器由 `frontend/src/jobs.ts` 跟进、刷新后经读接口恢复,服务重启不重放;`BackgroundJob.update(job_id)` 报阶段与计数,查询不重新执行任务。
+- 后台任务用 `watchJob`、`followJobProgress` 默认面板与 `jobActivityHtml` 的真实计数/未知总量显示,关注、来源扫描、链接检查和扫描采集共用;业务保留启动、终态回执和结果面板,不新增轮询循环。任务本体是 `jobs.BackgroundJob`,不加队列或调度依赖;浏览器由 `frontend/src/jobs.ts` 跟进,刷新后经读接口恢复。可恢复的采集任务由本机恢复记录重放,其他任务只保留终态;`BackgroundJob.update(job_id)` 报阶段与计数,查询不重新执行任务。
- 遗留层反馈控件 `noteHtml`、`progressHtml`、`gaugeHtml`、`projectBannerHtml` 与 `wireContextCard` 集中在共享 UI 模块;信息卡片用原生 Popover 与现有锚定菜单定位,不加浮层依赖。证据见 `reference-snapshots/vercel-geist-note-progress-switch-analytics.md`。
- 资源核对复用 `web_resource_sync` 的目录枚举、离线跳过、写前逐条复验与 BackgroundJob,覆盖 local、115、PikPak;失效记录的永久删除复用 `web_batch.purge_assets`,文件仍在盘上的行进 `blocked`。确认弹层复用 Fieldset、Note、Toast 与 confirmModal:失败留在弹层,危险动作初始聚焦取消,忙态阻止重入与关闭;不引入另一套对话框库。
- 新界面走 BoardUI/React(ADR-0031),遗留层共用的 Geist 控件随页面迁走,不引入 Geist React 运行时。覆盖式滚动条 `attachOverlayScrollbar`(滑块不占宽度)、Collapse 的 `wireCollapse`/`setCollapseOpen`、Geist Select 的 `selectFieldHtml`/`wireSelectField`、来源站标 `MEDIA_SOURCE_ICONS`,以及模板、骨架、确认框等其余共用控件的唯一实现在 `frontend/src/ui-kit/`,Application 与 React 页面直接引用共享源码,随 `/dist/peach-app.js` 发出一份;独立页面包只打入用到的控件;覆盖式滚动条与 `.ui-geist-scroller`(只给两端渐隐)可叠加;整页异步重绘复用导航代际隔离。
@@ -188,6 +188,10 @@ OneJAV、Free JAV Torrent 只给种子链接。这类条目经索引器同源的
## 独立测试包在线更新
+- 任务起跑与安装预约复用已固定的 filelock 4.1.1(MIT,Windows/macOS/Linux,无额外依赖)和原子 JSON。`update_tasks` 在同一数据目录内串行登记任务和预约安装,覆盖各服务进程、任务中心、后继领取和 `job_main` 批处理。安装请求触发采集任务在检查点保存并暂停,任务中心保留 `pending` 行;新采集请求进入等待。安装入口等在途步骤保存进度,随后停止自己的服务,不要求用户等待整轮任务结束。源码批处理保留 PID 锁,写完在途批次后等待安装,结束后由原进程继续。
+- 安装器在临时目录展开随包运行时,以 `--installer-prepare` 承接馆藏处理状态并暂停任务;预约归安装器持有,完成或取消时释放。在线更新将预约交给更新助手,切换目录和迁移完成后释放,失败回滚也释放。恢复轮询复用 APScheduler,安装取消时现有服务也会接回任务。不采用新任务队列或更新框架:任务语义、PyInstaller 目录切换和 Inno Setup 生命周期继续由已有实现承担。
+- `job_recovery` 保存馆藏处理范围、阶段、指定影片、时间轴密度、单部封面、关注、订阅和想要资料的请求;服务启动或安装结束后只领取未完成记录。暂停任务复用任务中心的同一行,已完成、失败和主动停止的任务不循环重试。馆藏预览在产物登记后保存影片检查点,元数据检查点跟随候选 CSV 成功落盘;未取得结果的项目不记完成。时间轴复用已有索引判定。恢复领取和新任务起跑共用安装闸门,数据仍留在本机 state 目录,不引入 ledger 迁移。
+
- 自动更新设置用 APScheduler(见「必须复用」表的定时轮询)、共享 HTTPX 发行查询、filelock 与原子 JSON 写入,安装走 `standalone_update`。按 [interval trigger](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/interval.html) 每分钟查是否到期,本机持久时间与文件锁协调多个服务;关闭、6/24/168 小时间隔与源码下载限制归 Peach。默认关闭,下载只准备安装,重启仍需确认;设置存 state 目录的 `automatic-updates.json`。
- 版本与资产信息用 GitHub Releases REST API(测试通道含预发布),查询与流式下载用项目 HTTPX,ZIP 解压用标准库,互斥用 FileLock。真实 Release 只读验过:只有已上传完整独立包的发布才进更新,查询不下载也不安装。
- 安装策略与进度归 Peach:下载校验后在程序同卷暂存,用户确认重启,复制出来的包内助手等原托盘退出再切换完整目录;失败保留或恢复旧目录。配置、数据库与媒体不进更新包。
diff --git a/scripts/build_app_entry.py b/scripts/build_app_entry.py
index dff70e079..f54062b46 100644
--- a/scripts/build_app_entry.py
+++ b/scripts/build_app_entry.py
@@ -104,6 +104,15 @@ def main(argv: list[str] | None = None) -> int:
if len(argv) == 2 and argv[1] in {"--installer-stop", "--installer-uninstall"}:
from peach.desktop_installer import main as installer_main
return installer_main(argv[1])
+ if len(argv) == 5 and argv[1] == "--installer-prepare":
+ from peach.desktop_installer import prepare
+ return prepare(Path(argv[2]), int(argv[3]), Path(argv[4]))
+ if len(argv) == 4 and argv[1] == "--installer-finish":
+ from peach.desktop_installer import finish_install
+ return finish_install(Path(argv[2]), int(argv[3]))
+ if len(argv) == 3 and argv[1] == "--installer-migrate":
+ from peach.desktop_installer import migrate_install
+ return migrate_install(Path(argv[2]))
if wants_cli(argv):
_prepare_console()
try:
diff --git a/scripts/installer/peach.iss b/scripts/installer/peach.iss
index 7d3f27d49..6d0fdbb7f 100644
--- a/scripts/installer/peach.iss
+++ b/scripts/installer/peach.iss
@@ -46,6 +46,7 @@ Name: "chs"; MessagesFile: "ChineseSimplified.isl"
[CustomMessages]
chs.StillRunning=Peach 仍在运行,未能自动退出。请从托盘菜单退出 Peach 后重试。
+chs.TaskCheckFailed=无法确认后台任务状态,安装已取消。请等待任务结束后重试。
chs.MigrationFailed=本地数据库未能更新到新版本,Peach 启动后可能出错。升级前的备份在数据目录的 database 文件夹里,文件名以 ledger.pre-migrate- 开头。
chs.DataKept=Peach 已卸载。设置、本地数据库和观看记录保留在 %1,需要时可手动删除;媒体文件不受影响。
chs.DirectoryOverlapsData=程序目录不能与 Peach 数据目录重叠。请选择独立的程序文件夹。
@@ -63,6 +64,7 @@ Type: filesandordirs; Name: "{app}\_internal"
[Files]
Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
+Source: "{#SourceDir}\*"; DestDir: "{tmp}\Peach-preflight"; Flags: dontcopy recursesubdirs createallsubdirs
[Icons]
Name: "{userprograms}\Peach"; Filename: "{app}\Peach.exe"; Parameters: "--show"
@@ -76,6 +78,30 @@ Filename: "{app}\Peach.exe"; Parameters: "--show"; Description: "{cm:LaunchProgr
Type: filesandordirs; Name: "{app}"
[Code]
+var
+ GuardPrepared: Boolean;
+
+function GetCurrentProcessId(): LongWord;
+ external '[email protected] stdcall';
+
+procedure FinishTaskGuard();
+var
+ ResultCode: Integer;
+begin
+ if GuardPrepared then
+ begin
+ if Exec(ExpandConstant('{tmp}\Peach-preflight\Peach.exe'),
+ '--installer-finish "' + ExpandConstant('{app}') + '" ' + IntToStr(GetCurrentProcessId()),
+ ExpandConstant('{tmp}\Peach-preflight'), SW_HIDE, ewWaitUntilTerminated, ResultCode) and (ResultCode = 0) then
+ GuardPrepared := False;
+ end;
+end;
+
+procedure DeinitializeSetup();
+begin
+ FinishTaskGuard();
+end;
+
function DataRoot(): String;
begin
Result := GetEnv('PEACH_DATA_ROOT');
@@ -117,15 +143,26 @@ end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
ResultCode: Integer;
+ ErrorText: AnsiString;
begin
Result := InstallationDirectoryError();
if Result <> '' then
Exit;
- { 退出码 1 是托盘没能退出;2 是不认这个参数的旧版本,交给 CloseApplications 处理。 }
- if FileExists(ExpandConstant('{app}\Peach.exe')) then
- if Exec(ExpandConstant('{app}\Peach.exe'), '--installer-stop', ExpandConstant('{app}'),
- SW_HIDE, ewWaitUntilTerminated, ResultCode) and (ResultCode = 1) then
- Result := CustomMessage('StillRunning');
+ if GuardPrepared then
+ Exit;
+ ExtractTemporaryFiles('{tmp}\Peach-preflight\*');
+ if not Exec(ExpandConstant('{tmp}\Peach-preflight\Peach.exe'),
+ '--installer-prepare "' + ExpandConstant('{app}') + '" ' + IntToStr(GetCurrentProcessId()) +
+ ' "' + ExpandConstant('{tmp}\Peach-preflight\prepare-error.txt') + '"',
+ ExpandConstant('{tmp}\Peach-preflight'), SW_HIDE, ewWaitUntilTerminated, ResultCode) or
+ (ResultCode <> 0) then
+ begin
+ Result := CustomMessage('TaskCheckFailed');
+ if LoadStringFromFile(ExpandConstant('{tmp}\Peach-preflight\prepare-error.txt'), ErrorText) then
+ Result := UTF8Decode(ErrorText);
+ end
+ else
+ GuardPrepared := True;
end;
procedure CurStepChanged(CurStep: TSetupStep);
@@ -134,10 +171,13 @@ var
begin
{ 服务启动时不迁移账本;覆盖安装换了程序,要在这里补上。没有账本的新机器不跑,
否则会凭空建出账本,首次设置页就再也不出现。migrate 自己会先备份。 }
- if (CurStep = ssPostInstall) and FileExists(DataRoot() + '\database\ledger.db') then
- if not Exec(ExpandConstant('{app}\Peach.exe'), 'migrate upgrade --yes', ExpandConstant('{app}'),
+ if CurStep = ssPostInstall then
+ if not Exec(ExpandConstant('{tmp}\Peach-preflight\Peach.exe'),
+ '--installer-migrate "' + ExpandConstant('{app}') + '"', ExpandConstant('{tmp}\Peach-preflight'),
SW_HIDE, ewWaitUntilTerminated, ResultCode) or (ResultCode <> 0) then
SuppressibleMsgBox(CustomMessage('MigrationFailed'), mbError, MB_OK, IDOK);
+ if CurStep = ssPostInstall then
+ FinishTaskGuard();
end;
function InitializeUninstall(): Boolean;
diff --git a/scripts/smoke_update_tasks.py b/scripts/smoke_update_tasks.py
new file mode 100644
index 000000000..e3c730ab4
--- /dev/null
+++ b/scripts/smoke_update_tasks.py
@@ -0,0 +1,128 @@
+"""仅用标准库和临时数据验证制品的升级保护、覆盖安装与任务恢复。"""
+from __future__ import annotations
+
+import argparse
+from contextlib import closing
+import hashlib
+import http.cookiejar
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import sqlite3
+import subprocess
+import urllib.request
+
+from smoke_desktop import complete_first_run, smoke_directory, smoke_environment, wait_for, wait_health
+
+
+def validate_installer_host():
+ assert os.environ.get('GITHUB_ACTIONS') == 'true', '安装包验收只允许在干净的 Actions runner 上运行'
+ import winreg
+ key = r'Software\Microsoft\Windows\CurrentVersion\Uninstall\{02D9748A-78F6-4866-AC75-918177194DAB}_is1'
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key):
+ raise AssertionError('已有 Peach 安装登记,停止验收')
+ except FileNotFoundError:
+ pass
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('executable', type=Path)
+ parser.add_argument('--old-executable', type=Path)
+ parser.add_argument('--installer', type=Path)
+ parser.add_argument('--evidence-dir', type=Path, default=Path('smoke-evidence'))
+ args = parser.parse_args()
+ executable = args.executable.resolve(strict=True)
+ if args.installer:
+ validate_installer_host()
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
+ with smoke_directory(args.evidence_dir.resolve()) as root:
+ application = root / '中文 程序目录/Peach'
+ old = (args.old_executable or executable).resolve(strict=True)
+ shutil.copytree(old.parent, application)
+ target = application / 'Peach.exe'
+ data, media = root / 'data', root / 'media'
+ media.mkdir()
+ environment = smoke_environment(data)
+ with socket.socket() as reservation:
+ reservation.bind(('127.0.0.1', 0))
+ port = reservation.getsockname()[1]
+ base = f'http://127.0.0.1:{port}'
+ log_path = root / 'runtime.log'
+ command = [str(target), 'serve', '--host', '127.0.0.1', '--port', str(port),
+ '--no-mdns', '--no-ledger-sync']
+ process = None
+ with log_path.open('wb') as log:
+ try:
+ process = subprocess.Popen([*command, '--setup'], cwd=root, env=environment, stdout=log, stderr=log)
+ wait_health(opener, base, process, log_path)
+ complete_first_run(opener, base, media, port, 'update-task-smoke-password')
+ process.terminate()
+ process.wait(timeout=20)
+ process = subprocess.Popen(command, cwd=root, env=environment, stdout=log, stderr=log)
+ wait_health(opener, base, process, log_path)
+ db = data / 'database/ledger.db'
+ config_before = (data / 'config.toml').read_bytes()
+ program_before = hashlib.sha256(target.read_bytes()).hexdigest()
+ with closing(sqlite3.connect(db)) as connection, connection:
+ cursor = connection.execute(
+ "INSERT INTO task_run(task_key,trigger,status,mutex_key,pid,host,started_at,heartbeat_at) "
+ "VALUES('library-processing','manual','running','library-processing',?,?,datetime('now'),datetime('now'))",
+ (process.pid, socket.gethostname()))
+ run_id = cursor.lastrowid
+ state = data / 'state/library-processing.json'
+ state.write_text(json.dumps({'job_id': 'interrupted-fixture', 'status': 'running',
+ 'requested_stage': 'scan', 'last_progress_at': 1}), encoding='utf-8')
+ installer_command = None
+ if args.installer:
+ installer_command = [str(args.installer.resolve()), '/VERYSILENT', '/SUPPRESSMSGBOXES',
+ '/NORESTART', f'/DIR={application}', f'/LOG={root / "install.log"}']
+ subprocess.run(installer_command, env=environment, timeout=240, check=True)
+ else:
+ error = root / 'preflight-error.txt'
+ helper = subprocess.run([str(executable), '--installer-prepare', str(application),
+ str(os.getpid()), str(error)], env=environment, timeout=150)
+ assert helper.returncode == 0, error.read_text(encoding='utf-8') if error.exists() else helper.returncode
+ assert hashlib.sha256(target.read_bytes()).hexdigest() == program_before
+ process.wait(timeout=20)
+ with closing(sqlite3.connect(db)) as connection, connection:
+ assert connection.execute('SELECT status FROM task_run WHERE id=?', (run_id,)).fetchone() == ('pending',)
+ if not installer_command:
+ shutil.copytree(executable.parent, application, dirs_exist_ok=True)
+ subprocess.run([str(executable), '--installer-finish', str(application), str(os.getpid())],
+ env=environment, timeout=30, check=True)
+ assert (data / 'config.toml').read_bytes() == config_before
+ recovery = data / 'state/job-recovery/library-processing.json'
+ assert json.loads(recovery.read_text(encoding='utf-8'))['request'] == {'stage': 'scan'}
+ process = subprocess.Popen(command, cwd=root, env=environment, stdout=log, stderr=log)
+ wait_health(opener, base, process, log_path)
+ def recovered():
+ result = json.loads(recovery.read_text(encoding='utf-8'))
+ assert result['status'] not in ('failed', 'blocked'), result
+ return result if result['status'] == 'complete' else None
+ result = wait_for(recovered, '未完成任务自动恢复', timeout=60)
+ assert result['job_id'] == 'interrupted-fixture'
+ with closing(sqlite3.connect(db)) as connection:
+ assert connection.execute(
+ "SELECT COUNT(*) FROM task_run WHERE task_key='library-processing' AND status='succeeded'").fetchone()[0] == 1
+ assert connection.execute('SELECT status FROM task_run WHERE id=?', (run_id,)).fetchone() == ('succeeded',)
+ print(json.dumps({'ok': True, 'checks': ['active-task-install-accepted', 'task-paused',
+ 'configuration-retained', 'same-task-resumed-once',
+ 'installer-overlay' if installer_command else 'zip-overlay']}), flush=True)
+ finally:
+ if process is not None and process.poll() is None:
+ process.terminate()
+ process.wait(timeout=20)
+ if args.installer and (application / 'unins000.exe').exists():
+ subprocess.run([str(application / 'unins000.exe'), '/VERYSILENT', '/SUPPRESSMSGBOXES',
+ '/NORESTART'], env=environment, timeout=120, check=True)
+ wait_for(lambda: not application.exists(), '卸载临时验收程序', timeout=120)
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 705c2a756..8a776ff5e 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -112,7 +112,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"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",
- "test_job_status.py", "test_jobs.py", "test_task_runs.py", "test_followups.py",
+ "test_job_status.py", "test_jobs.py", "test_task_runs.py", "test_followups.py", "test_update_tasks.py",
"test_task_center_integration.py", "test_reference_updates.py",
"test_repo_hygiene.py", "test_seed_pack.py", "test_seed_followup.py",
"test_review_csv.py", "test_jav_code_domain.py", "test_organize.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index 0e60988b5..2c28754e5 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -140,6 +140,9 @@ def _restore_task_center(contract) -> None:
后继是例外:它重新排队而不判 `interrupted`,冻在终态就再也没有重试的机会
(ADR-0040 第六条)。排着的那些也在这一步被叫醒,接着跑完。
"""
+ from .job_recovery import reconcile_paused
+ if contract.task_runs.enabled:
+ reconcile_paused(contract.db_path)
recovered = contract.task_runs.recover_interrupted()
if recovered:
LOGGER.info("task center recovered %s interrupted run(s)", len(recovered))
@@ -163,6 +166,9 @@ def _start_ledger_services(settings: PeachSettings, contract, services) -> bool:
status["database"], status["schema"])
return False
_restore_task_center(contract)
+ from .web_job_recovery import restore
+ if contract.task_runs.enabled:
+ restore(contract)
for service in services:
service.start()
return True
@@ -302,6 +308,8 @@ def create_app(
unavailable_message="订阅源拉取只在写入端可用",
)
contract.feed_scheduler = feed_scheduler
+ from .web_job_recovery import RecoveryService
+ recovery_service = RecoveryService(contract, available=_writer(sync))
contract.header_repairs = header_repairs
contract.transcode_service = transcode_service
# 只读端不写任务中心:`task_run` 也在账本里,reader 往里写会造成无法自动合并的
@@ -343,7 +351,7 @@ def create_app(
ledger_ready = False
if settings.configured:
ledger_ready = _start_ledger_services(settings, contract,
- (follow_scheduler, feed_scheduler, push_discovery, downloads))
+ (follow_scheduler, feed_scheduler, push_discovery, downloads, recovery_service))
automatic_updates.start()
mount_reachability.start()
_app.state.ledger_background_ready = ledger_ready
@@ -363,6 +371,7 @@ def create_app(
aggregate_stop.set()
loop.set_exception_handler(previous_error_handler)
warmup.cancel()
+ recovery_service.stop()
follow_scheduler.stop()
feed_scheduler.stop()
automatic_updates.stop()
diff --git a/src/peach/desktop_installer.py b/src/peach/desktop_installer.py
index bb51d6f4c..2bc8bee0f 100644
--- a/src/peach/desktop_installer.py
+++ b/src/peach/desktop_installer.py
@@ -116,3 +116,43 @@ def main(action: str) -> int:
if action == "--installer-uninstall":
remove_shortcuts(program)
return 0
+
+
+def prepare(program: Path, owner: int, error_file: Path) -> int:
+ """安装器使用随包携带的运行时预检,程序目录里的旧版本无需支持此协议。"""
+ from . import settings_file, update_tasks, job_recovery
+ from .fsutil import atomic_write_text
+ config = settings_file.load_config(project_root=program)
+ db = config.directory('database') / 'ledger.db'
+ token = None
+ try:
+ token = update_tasks.reserve(db, owner=owner)
+ previous = job_recovery.legacy_library_request(db)
+ update_tasks.wait_quiescent(db)
+ if not stop(program):
+ raise update_tasks.UpdateBusy('Peach 尚未退出,安装未完成。请稍后重试。')
+ job_recovery.import_legacy_library(db, previous)
+ return 0
+ except Exception as exc:
+ if token:
+ update_tasks.release(db, token)
+ atomic_write_text(error_file, str(exc))
+ return 1
+
+
+def finish_install(program: Path, owner: int) -> int:
+ """安装完成或取消后撤销属于这个安装器的预约。"""
+ from . import settings_file, update_tasks
+ db = settings_file.load_config(project_root=program).directory('database') / 'ledger.db'
+ update_tasks.release_owner(db, owner)
+ return 0
+
+
+def migrate_install(program: Path) -> int:
+ """按实际数据目录迁移已有账本,空白安装不创建数据库。"""
+ from . import settings_file
+ from .cli import main as cli_main
+ db = settings_file.load_config(project_root=program).directory('database') / 'ledger.db'
+ if not db.is_file():
+ return 0
+ return cli_main(['migrate', 'upgrade', '--yes', '--db', str(db)])
diff --git a/src/peach/follow_scheduler.py b/src/peach/follow_scheduler.py
index 321eba095..eaa55f577 100644
--- a/src/peach/follow_scheduler.py
+++ b/src/peach/follow_scheduler.py
@@ -12,6 +12,7 @@ from typing import Callable
from apscheduler.jobstores.base import JobLookupError
from apscheduler.schedulers.background import BackgroundScheduler
+from .update_tasks import UpdateBusy
LOGGER = logging.getLogger(__name__)
@@ -170,7 +171,10 @@ class FollowUpdateScheduler:
# (`w_follow_check` 按 `automatic` 传 `trigger="scheduled"`),开始、进度、
# 结束三样都在里面。这里不再记第二条:轮询和手动检查是同一件事的两种发起
# 方式,各记一条在活动页上就成了两轮。
- result = self.run_check()
+ try:
+ result = self.run_check()
+ except UpdateBusy:
+ result = {'busy': True}
if result.get("busy"):
# 锁被另一次检查占着是互斥的正常结果,不是故障:手动检查正在跑的
# 时候自动这一轮什么也没做。这里不抛异常:抛了界面就把它显示成
diff --git a/src/peach/followups.py b/src/peach/followups.py
index ae219db0c..de6ac31d7 100644
--- a/src/peach/followups.py
+++ b/src/peach/followups.py
@@ -146,6 +146,7 @@ class FollowupRunner:
self._lock = threading.Lock()
self._threads: dict[str, threading.Thread] = {}
self._stopping = False
+ self._paused_for_update = False
# -- 对外 --------------------------------------------------------------
@@ -184,6 +185,11 @@ class FollowupRunner:
if thread.is_alive():
thread.join(timeout)
+ def resume_after_update(self) -> None:
+ if self._paused_for_update:
+ self._paused_for_update = False
+ self.wake()
+
def drain(self) -> int:
"""在当前线程里把所有通道排着的后继跑完,返回跑了几条。
@@ -205,6 +211,10 @@ class FollowupRunner:
while not self._stopping:
run = self.store.claim_followup(keys)
if run is None:
+ from .update_tasks import is_pausing
+ db = getattr(getattr(self.store, 'database', None), 'db_path', None)
+ if isinstance(db, Path) and is_pausing(db):
+ self._paused_for_update = True
return
self._execute(run)
diff --git a/src/peach/job_recovery.py b/src/peach/job_recovery.py
new file mode 100644
index 000000000..24430319d
--- /dev/null
+++ b/src/peach/job_recovery.py
@@ -0,0 +1,162 @@
+"""将可重放任务的参数保存在本机,服务启动时只领取未完成的记录。"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+from contextvars import ContextVar
+from pathlib import Path
+
+from .fsutil import atomic_write_text
+from .update_tasks import admission, state_for, UpdateBusy, _mutex
+
+LOGGER = logging.getLogger(__name__)
+current_run = ContextVar('peach_resuming_run', default=None)
+current_job_id = ContextVar('peach_resuming_job_id', default=None)
+
+
+def _path(db: Path, key: str) -> Path:
+ if not key or any(c not in "abcdefghijklmnopqrstuvwxyz0123456789-" for c in key):
+ raise ValueError("任务恢复标识无效")
+ return state_for(db).parent / "job-recovery" / (key + ".json")
+
+
+def read(db: Path, key: str) -> dict:
+ try:
+ data = json.loads(_path(db, key).read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else {}
+ except FileNotFoundError:
+ return {}
+ except (OSError, ValueError):
+ return {'status': 'blocked', 'error': '任务恢复记录无法读取,请重新发起任务。'}
+
+
+def save(db: Path, key: str, job_id: str, request: dict, *, run_id=None, waiting=False) -> None:
+ atomic_write_text(_path(db, key), json.dumps({
+ "job_id": job_id, "pid": -1 if waiting else os.getpid(), "status": "active",
+ "request": request, 'run_id': run_id}, ensure_ascii=False))
+
+
+def finish(db: Path, key: str, job_id: str, status: str) -> None:
+ with _mutex(state_for(db)):
+ data = read(db, key)
+ if data.get("job_id") == job_id:
+ data["status"] = status
+ atomic_write_text(_path(db, key), json.dumps(data, ensure_ascii=False))
+
+
+def cancel(db: Path, key: str) -> None:
+ with _mutex(state_for(db)):
+ data = read(db, key)
+ if data.get('run_id') is not None:
+ from .task_runs import TaskRunStore
+ TaskRunStore(db).finish(data['run_id'], 'cancelled', error='用户停止任务')
+ _path(db, key).unlink(missing_ok=True)
+
+
+def waiting(db: Path, key: str, job_id: str) -> None:
+ with _mutex(state_for(db)):
+ data = read(db, key)
+ if data.get('job_id') == job_id:
+ data['pid'] = -1
+ atomic_write_text(_path(db, key), json.dumps(data, ensure_ascii=False))
+
+
+def request_pause(db: Path) -> None:
+ """在安装事务内保留暂停意图,进程退出后仍能接回同一条任务。"""
+ for path in (state_for(db).parent / 'job-recovery').glob('*.json'):
+ data = read(db, path.stem)
+ if data.get('status') == 'active':
+ data['pause_requested'] = True
+ atomic_write_text(path, json.dumps(data, ensure_ascii=False))
+
+
+def reconcile_paused(db: Path) -> None:
+ from .jobs import process_alive
+ from .task_runs import TaskRunStore
+ with _mutex(state_for(db)):
+ for path in (state_for(db).parent / 'job-recovery').glob('*.json'):
+ data = read(db, path.stem)
+ pid = data.get('pid')
+ if (data.get('status') == 'active' and data.get('pause_requested')
+ and isinstance(pid, int) and not process_alive(pid)):
+ if data.get('run_id') is not None:
+ TaskRunStore(db).suspend(data['run_id'])
+ waiting(db, path.stem, data['job_id'])
+
+
+def resume(db: Path, handlers: dict) -> list[str]:
+ """领取与起跑在同一把锁内;失败保留参数但不循环重试。"""
+ from .jobs import process_alive
+ resumed = []
+ for key, handler in handlers.items():
+ try:
+ with admission(db):
+ data = read(db, key)
+ pid = data.get("pid")
+ if (data.get("status") != "active" or not isinstance(data.get("request"), dict)
+ or (isinstance(pid, int) and pid != os.getpid() and process_alive(pid))):
+ continue
+ # 当前进程自己的新任务不属于启动恢复。
+ if pid == os.getpid():
+ continue
+ try:
+ context = current_run.set(data.get('run_id'))
+ identity = current_job_id.set(data.get('job_id'))
+ try:
+ result = handler(data["request"])
+ if result is None and read(db, key) == data:
+ finish(db, key, data['job_id'], 'complete')
+ if data.get('run_id') is not None:
+ from .task_runs import TaskRunStore
+ TaskRunStore(db).finish(data['run_id'], 'succeeded')
+ finally:
+ current_run.reset(context)
+ current_job_id.reset(identity)
+ except Exception as exc:
+ if data.get('run_id') is not None:
+ from .task_runs import TaskRunStore
+ TaskRunStore(db).finish(data['run_id'], 'failed', error=str(exc))
+ data.update(status="blocked", error=str(exc))
+ atomic_write_text(_path(db, key), json.dumps(data, ensure_ascii=False))
+ LOGGER.warning("任务 %s 未能恢复:%s", key, exc)
+ else:
+ resumed.append(key)
+ except UpdateBusy:
+ break
+ return resumed
+
+
+def legacy_library_request(db: Path) -> dict:
+ """读取已在执行的馆藏处理范围,供安装助手承接已有状态文件。"""
+ if read(db, 'library-processing').get('status') == 'active':
+ return {}
+ path = state_for(db).parent / 'library-processing.json'
+ try:
+ data = json.loads(path.read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) and data.get('status') == 'running' else {}
+
+
+def import_legacy_library(db: Path, previous: dict) -> None:
+ if not previous or read(db, 'library-processing').get('status') == 'active':
+ return
+ path = state_for(db).parent / 'library-processing.json'
+ try:
+ latest = json.loads(path.read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ latest = previous
+ if latest.get('status') == 'complete':
+ return
+ from .task_runs import TaskRunStore
+ store = TaskRunStore(db)
+ runs = store.query(status='active', task_key='library-processing', limit=1)
+ run_id = runs[0].id if runs else None
+ if run_id is not None:
+ store.suspend(run_id)
+ request = {'stage': previous.get('requested_stage') or 'all'}
+ if previous.get('asset_ids'):
+ request['asset_ids'] = previous['asset_ids']
+ save(db, 'library-processing', previous.get('job_id') or 'library-processing',
+ request, run_id=run_id, waiting=True)
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index 3897e4209..37990b7f8 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -8,7 +8,7 @@ import threading
import time
import uuid
from collections.abc import Callable, Iterator
-from contextlib import contextmanager
+from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from pathlib import Path
@@ -25,6 +25,11 @@ class DiskSpaceDenied(JobPolicyError):
exit_code = 3
+class JobPaused(JobPolicyError):
+ """安装期间在任务检查点暂停,原参数保留用于恢复。"""
+ exit_code = 3
+
+
class JobAlreadyRunning(JobPolicyError):
exit_code = 0
@@ -112,12 +117,16 @@ class DiskGuard:
self.minimum_gb = float(minimum_gb)
self.interval_secs = float(interval_secs)
self._next_check = 0.0
+ from .update_tasks import current_db
+ self._pause_db = current_db.get()
def free_gb(self) -> float:
return shutil.disk_usage(self.path).free / 1024**3
def check(self, force: bool = False) -> float | None:
"""到期就复查;返回本次读到的可用 GiB,未到期返回 None。触线抛 DiskSpaceDenied。"""
+ from .update_tasks import check_pause
+ check_pause(self._pause_db)
now = time.monotonic()
if not force and now < self._next_check:
return None
@@ -286,6 +295,8 @@ class BackgroundJob:
#: job_id → task_run id。结算读这一份而不是读状态:状态可能已经被下一轮顶掉,
#: 而被顶掉的那一轮同样要有人给它收尾。
self._run_ids: dict[str, int] = {}
+ self._activity_files: dict[str, Path] = {}
+ self._recoverable: set[str] = set()
#: 摘 run id 与把那一行写成结束是同一件事:只摘不写完就放手的话,另一个线程
#: 看见 id 没了以为已经收过尾,紧接着开的下一轮会撞上那一行还没释放的互斥键。
self._close_lock = threading.Lock()
@@ -295,6 +306,10 @@ class BackgroundJob:
with self.lock:
return copy.deepcopy(self.state) if self.state is not None else None
+ def _database_path(self) -> Path | None:
+ value = getattr(getattr(self.runs, 'database', None), 'db_path', None)
+ return Path(value) if isinstance(value, (str, Path)) else None
+
def update(self, job_id: str, **fields: object) -> bool:
"""状态仍属于 `job_id` 时改字段;已经被顶掉就什么都不做并返回 False。"""
with self.editing(job_id) as state:
@@ -313,6 +328,9 @@ class BackgroundJob:
退出时把进度同步进 `task_run`,写库在锁外:那一步要拿数据库的写锁,套在本类
的锁里面就多了一组取锁顺序,而进度本来不需要和状态原子。节流由 store 做。
"""
+ if job_id in self._recoverable:
+ from .update_tasks import check_pause
+ check_pause(self._database_path())
with self.lock:
state = self.state
current = state if state is not None and state[self.id_key] == job_id else None
@@ -369,7 +387,36 @@ class BackgroundJob:
return summary
def start(self, fn: Callable[[str], None], *, initial: dict | None = None,
- restart: bool = False, trigger: str = "manual") -> dict:
+ restart: bool = False, trigger: str = "manual", recovery: dict | None = None) -> dict:
+ from .update_tasks import admission, UpdateBusy
+ db = self._database_path()
+ try:
+ with admission(db) if db is not None else nullcontext():
+ return self._start(fn, initial=initial, restart=restart, trigger=trigger, recovery=recovery)
+ except UpdateBusy:
+ if db is None or recovery is None:
+ raise
+ return self._queue(recovery, initial)
+
+ def _queue(self, recovery, initial):
+ from .job_recovery import save, read
+ from .update_tasks import _mutex, state_for
+ db = self._database_path()
+ with _mutex(state_for(db)), self.lock:
+ if self.state is not None and self.state.get('status') == 'running':
+ return copy.deepcopy(self.state)
+ existing = read(db, self.task_key)
+ job_id = existing.get('job_id') if existing.get('status') == 'active' else uuid.uuid4().hex
+ if existing.get('status') != 'active':
+ save(db, self.task_key, job_id, recovery, waiting=True)
+ self.state = {self.id_key: job_id, 'status': 'running', 'run_id': None,
+ **(initial or {}), 'waiting_for_update': True,
+ 'stage': '等待安装完成后继续', 'error': '',
+ 'message': '任务将在安装完成后自动继续。'}
+ return copy.deepcopy(self.state)
+
+ def _start(self, fn: Callable[[str], None], *, initial: dict | None = None,
+ restart: bool = False, trigger: str = "manual", recovery: dict | None = None) -> dict:
"""跑一轮,返回启动后(或原有)状态的深拷贝。
已经在跑,或者已经有结果而调用方没要求 `restart`,都原样返回现状——重复点击
@@ -384,9 +431,12 @@ class BackgroundJob:
job_id = ""
with self.lock:
state = self.state
+ if state is not None and state.get('waiting_for_update'):
+ state = None
previous = state
if state is None or (restart and state["status"] != "running"):
- job_id = uuid.uuid4().hex
+ from .job_recovery import current_job_id
+ job_id = current_job_id.get() or uuid.uuid4().hex
state = {self.id_key: job_id, "status": "running", "run_id": None,
"started_at": time.time(), "error": "", **(initial or {})}
self.state = state
@@ -409,7 +459,18 @@ class BackgroundJob:
self._settle_from(previous[self.id_key], previous, superseded=True)
try:
self._open_run(job_id, trigger, snapshot)
- except TaskRunConflict:
+ if (db := self._database_path()) is not None:
+ from .update_tasks import register
+ self._activity_files[job_id] = register(db, self.task_key)
+ if recovery is not None:
+ from .job_recovery import save
+ save(db, self.task_key, job_id, recovery, run_id=self._run_ids.get(job_id))
+ self._recoverable.add(job_id)
+ except Exception:
+ self._close_run(job_id, 'failed', error='任务未能启动')
+ activity = self._activity_files.pop(job_id, None)
+ if activity is not None:
+ activity.unlink(missing_ok=True)
# 线程还没起,这一轮什么都没做过,撤干净再把冲突交出去。
with self.lock:
if self.state is not None and self.state[self.id_key] == job_id:
@@ -442,7 +503,7 @@ class BackgroundJob:
self.runs.finish(run_id, status, summary=summary, error=error)
self.runs.prune(self.task_key)
- def stop(self, timeout: float | None = 2.0) -> None:
+ def stop(self, timeout: float | None = 2.0, *, resume: bool = True) -> None:
"""丢掉状态并等线程收工,用于服务关停。
线程是 daemon,本来也挡不住进程退出;清状态的意义是让在途的 worker 下一次
@@ -453,6 +514,9 @@ class BackgroundJob:
在途那一轮在表里记成 `cancelled`:进程是有序退出的,不是被打断,下次启动的
租约恢复也就不该再把它算成一次故障。
"""
+ if not resume and (db := self._database_path()) is not None:
+ from .job_recovery import cancel
+ cancel(db, self.task_key)
with self.lock:
state = self.state
job_id = state[self.id_key] if state is not None else ""
@@ -464,25 +528,61 @@ class BackgroundJob:
if thread is not None and thread.is_alive():
thread.join(timeout)
- def start_result(self, fn: Callable[[], dict]) -> dict:
+ def start_result(self, fn: Callable[[], dict], *, recovery: dict | None = None) -> dict:
"""执行一次操作并保存终态回执;重复提交只返回进行中的同一任务。"""
def work(job_id):
result = fn()
self.update(job_id, **result, status=(
"complete" if result.get("ok", True) else "failed"),
completed_at=time.time())
- return self.start(work, restart=True)
+ return self.start(work, restart=True, recovery=recovery)
def _run(self, fn: Callable[[str], None], job_id: str) -> None:
+ from .update_tasks import current_db
+ from .job_recovery import current_run, current_job_id
+ parent_run = current_run.set(None)
+ parent_job = current_job_id.set(None)
+ context = current_db.set(self._database_path() if job_id in self._recoverable else None)
try:
+ from .update_tasks import check_pause
+ check_pause(current_db.get())
fn(job_id)
+ except JobPaused:
+ with self.lock:
+ if self.state is not None and self.state.get(self.id_key) == job_id:
+ self.state.update(waiting_for_update=True, stage='等待安装完成后继续', error='',
+ message='任务已暂停,安装完成后自动继续。')
except Exception as error: # 后台失败必须变成可轮询的状态,不能只留在日志里
# 抛出来就是没跑完:途中声明过的后继作废,结算时一条都不派。
- self.update(job_id, status="failed",
- error=f"{type(error).__name__}: {error}",
- followups=[], completed_at=time.time())
+ with self.lock:
+ if self.state is not None and self.state.get(self.id_key) == job_id:
+ self.state.update(status='failed', error=f'{type(error).__name__}: {error}',
+ followups=[], completed_at=time.time())
finally:
- self._settle(job_id)
+ try:
+ self._finish_execution(job_id)
+ finally:
+ current_db.reset(context)
+ current_run.reset(parent_run)
+ current_job_id.reset(parent_job)
+
+ def _finish_execution(self, job_id):
+ from .update_tasks import _mutex, state_for
+ db = self._database_path()
+ with _mutex(state_for(db)) if db is not None else nullcontext():
+ try:
+ self._settle(job_id)
+ state = self.snapshot() or {}
+ if (db is not None and job_id in self._recoverable
+ and state.get(self.id_key) == job_id and not state.get('waiting_for_update')):
+ from .job_recovery import finish
+ finish(db, self.task_key, job_id,
+ 'failed' if state.get('status') == 'failed' else 'complete')
+ finally:
+ activity = self._activity_files.pop(job_id, None)
+ if activity is not None:
+ activity.unlink(missing_ok=True)
+ self._recoverable.discard(job_id)
def _settle(self, job_id: str) -> None:
"""按域自己落下的终态结算 `task_run`。
@@ -492,6 +592,13 @@ class BackgroundJob:
把互斥键一起堵死到下次服务重启。
"""
state = self.snapshot() or {}
+ if state.get(self.id_key) == job_id and state.get('waiting_for_update'):
+ from .job_recovery import waiting
+ run_id = self._run_ids.pop(job_id, None)
+ if self.runs is not None and run_id is not None:
+ self.runs.suspend(run_id)
+ waiting(self._database_path(), self.task_key, job_id)
+ return
if state.get(self.id_key) != job_id:
# 已经被 `start` 在顶替的那一刻收过尾了,这里再收一次是空操作。
self._close_run(job_id, "cancelled", error="这一轮已被新的任务顶替")
@@ -561,9 +668,29 @@ def job_main(build_parser, run, argv: list[str] | None = None) -> int:
约定;散成三份,下一个脚本照抄时漏掉锁或吞掉退出码都不会有人发现。
"""
args = build_parser().parse_args(argv)
+ from .update_tasks import UpdateBusy
try:
+ from .update_tasks import activity
+ db = Path(getattr(args, 'db', Path(args.lock).resolve().parent / 'ledger.db'))
with PidFileLock(args.lock):
- return run(args)
+ return _run_batch_with_updates(db, Path(args.lock).stem, run, args)
except JobPolicyError as exc:
print(f"[stop] {exc}")
return exc.exit_code
+ except UpdateBusy as exc:
+ print(f"[stop] {exc}")
+ return 3
+
+
+def _run_batch_with_updates(db, label, run, args):
+ from .update_tasks import activity, is_pausing, wait_for_installation, UpdateBusy
+ while True:
+ try:
+ with activity(db, label):
+ result = run(args)
+ if result == 0 or not is_pausing(db):
+ return result
+ except (JobPaused, UpdateBusy):
+ pass
+ print('[pause] 任务进度已保留,安装完成后自动继续。')
+ wait_for_installation(db)
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 0f16cf0bd..8bfc7ca09 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -654,7 +654,7 @@ def decorate(state, *, now=None):
path=str(row.get('path') or ''), message=str(row.get('message') or ''))
for row in legacy[:ISSUE_PREVIEW_LIMIT]]
state['issues_truncated'] = len(legacy) > ISSUE_PREVIEW_LIMIT
- if state.get('status') != 'running':
+ if state.get('status') != 'running' or state.get('waiting_for_update'):
return state
now = time.time() if now is None else now
started = state.get('current_started_at') or state.get('last_progress_at') or state.get('started_at')
@@ -1753,7 +1753,8 @@ def _generate_preview(config, row, database, resolver, *, progress):
return bool(result.rowcount)
-def _generate_previews(config, rows, database, *, update, issue, guard):
+def _generate_previews(config, rows, database, *, update, issue, guard,
+ completed=(), checkpoint=lambda row: None):
"""只读本机视频;来源失败与抽帧失败各自保留可重试项目。"""
if database is None:
return 0
@@ -1761,6 +1762,8 @@ def _generate_previews(config, rows, database, *, update, issue, guard):
resolver = FFmpegResolver(config.directory('tools') / 'ffmpeg')
made = 0
for index, row in enumerate(rows):
+ if _checkpoint_key(row) in completed:
+ continue
def progress(row=row, index=index, made=made):
guard.check()
update(stage='生成预览图', checked=index, total=len(rows), previews=made,
@@ -1770,6 +1773,7 @@ def _generate_previews(config, rows, database, *, update, issue, guard):
progress()
try:
made += int(_generate_preview(config, row, database, resolver, progress=progress))
+ checkpoint(row)
except InterruptedError:
raise
except (OSError, ValueError, subprocess.SubprocessError) as error:
@@ -1782,10 +1786,51 @@ def _generate_previews(config, rows, database, *, update, issue, guard):
return made
+def _checkpoint_key(row):
+ return f"{row['id']}:{row['path']}"
+
+
+class _LibraryCheckpoints:
+ """只有预览登记或候选落盘成功才提交影片检查点。"""
+
+ def __init__(self, state, previous, database):
+ previous = previous or {}
+ self.state = state
+ self.completed = {phase: set(previous.get(phase) or [])
+ for phase in ('completed_previews', 'completed_metadata')}
+ self.pending_metadata = set()
+ self.entity_watermark = previous.get('entity_watermark')
+ if self.entity_watermark is None:
+ self.entity_watermark = _entity_watermark(database)
+ state['entity_watermark'] = self.entity_watermark
+ for phase, keys in self.completed.items():
+ state[phase] = sorted(keys)
+
+ def mark(self, phase, row, flush):
+ self.completed[phase].add(_checkpoint_key(row))
+ self.state[phase] = sorted(self.completed[phase])
+ flush(force=True)
+
+ def queue_metadata(self, row, entries, issues_before):
+ if entries and self.state['issue_count'] == issues_before:
+ self.pending_metadata.add(_checkpoint_key(row))
+
+ def commit_metadata(self, flush):
+ self.completed['completed_metadata'].update(self.pending_metadata)
+ self.pending_metadata.clear()
+ self.state['completed_metadata'] = sorted(self.completed['completed_metadata'])
+ flush(force=True)
+
+ def remaining_metadata(self, rows):
+ return ((index, row) for index, row in enumerate(rows)
+ if _checkpoint_key(row) not in self.completed['completed_metadata'])
+
+
def process_library(config, db_path, candidate_root, cover_root, *, location='configured',
report=lambda state: None, provider_factory=None, job_id=None,
retry_ids=None, active=lambda: True, stage=ALL_STAGES,
- database=None, route_overrides=None, state_file=None, asset_ids=None):
+ database=None, route_overrides=None, state_file=None, asset_ids=None,
+ resume_state=None):
"""登记文件与确定的番号,外部资料保留为可复核候选。
`retry_ids` 为 `None` 时处理整个馆藏;给定时只处理这些项目(上一任务记录的
@@ -1817,7 +1862,8 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
targeted = retrying or selected_ids is not None
chosen_ids = selected_ids if selected_ids is not None else list(dict.fromkeys(map(int, retry_ids or [])))
scope_ids = chosen_ids if targeted else None
- with FileLock(str(state_path(config)) + '.lock', timeout=0):
+ from .update_tasks import activity
+ with activity(Path(db_path), 'library-processing'), FileLock(str(state_path(config)) + '.lock', timeout=0):
state = dict(job_id=job_id or uuid.uuid4().hex, status='running',
stage='读取本地资料' if retrying else '扫描文件',
checked=0, total=0, scanned=0, probed=0, identified=0, candidates=0, covers=0, previews=0,
@@ -1830,7 +1876,8 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
followups=[],
started_at=time.time(), error='')
# 实体表的水位在开工前记一次:比它大的实体就是这一轮建出来的(`_entity_followups`)。
- entity_watermark = _entity_watermark(database)
+ checkpoints = _LibraryCheckpoints(state, resume_state, database)
+ entity_watermark = checkpoints.entity_watermark
# 每行这一轮换上了几张封面,`(asset_id, 张数)`:换上了的作品,女优可能截得出更清楚的脸。
covered = []
log_path = _processing_issue_log(config, path, state['job_id'], state_file is not None)
@@ -1896,7 +1943,9 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
rows, genre_decisions = _collection_rows(
db_path, locations=locations, online_roots=sources.online_roots, asset_ids=scope_ids)
if stage in (ALL_STAGES, COLLECT_STAGE, PREVIEWS_STAGE):
- _generate_previews(config, rows, database, update=update, issue=issue, guard=guard)
+ _generate_previews(config, rows, database, update=update, issue=issue, guard=guard,
+ completed=checkpoints.completed['completed_previews'],
+ checkpoint=lambda row: checkpoints.mark('completed_previews', row, flush_state))
if stage == PREVIEWS_STAGE:
update(status='failed' if state['issue_count'] else 'complete', stage='处理结束',
completed_at=time.time(), error=issue_summary(state['issue_count'], state['paused_count']))
@@ -1914,9 +1963,11 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
write_rows(output, FIELDS, groups.values(), atomic=True)
csv_dirty = False
csv_written_at = time.monotonic()
+ checkpoints.commit_metadata(flush_state)
- for index, row in enumerate(rows):
+ for index, row in checkpoints.remaining_metadata(rows):
guard.check()
+ issues_before = state['issue_count']
update(stage='读取本地资料', checked=index, total=len(rows),
current_asset_id=row['id'], current_asset_name=Path(str(row['name'] or '')).name,
current_action='reading_local', current_started_at=time.time(),
@@ -1931,6 +1982,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
update(checked=index + 1, candidates=len(scoped_groups()),
current_asset_id=None, current_asset_name='', current_action='',
current_started_at=None, current_deadline_at=None)
+ checkpoints.mark('completed_metadata', row, flush_state)
continue
video = translate_ledger_path(row['path'])
# 文件在不在看目录列表,不单独 stat:一部片一个文件夹的网盘上,那是每行一半的往返。
@@ -1998,6 +2050,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co
local_fields)
if entries:
csv_dirty = True
+ checkpoints.queue_metadata(row, entries, issues_before)
flush_candidates()
update(checked=index + 1, candidates=len(scoped_groups()),
current_asset_id=None, current_asset_name='', current_action='',
diff --git a/src/peach/routes_api.py b/src/peach/routes_api.py
index 68229d536..1618e0a37 100644
--- a/src/peach/routes_api.py
+++ b/src/peach/routes_api.py
@@ -29,6 +29,7 @@ from . import push_discovery, web_contract, web_tasks
from .field_owners import RevisionConflict
from .interaction import reveal_path
from .jobs import TaskRunConflict
+from .update_tasks import UpdateBusy
from .platform import is_unmapped, translate_ledger_path
from .providers import ProviderUnavailable
from .routes_auth import require_auth
@@ -300,6 +301,8 @@ def api_get(request: Request, route: str, args: dict[str, str] = Depends(require
return payload
except TaskRunConflict as exc:
return _conflict(exc)
+ except UpdateBusy as exc:
+ return JSONResponse({'error': 'update in progress', 'message': str(exc)}, status_code=409)
except KeyError:
return JSONResponse({"error": "not found"}, status_code=404)
except (TypeError, ValueError) as exc:
@@ -336,6 +339,8 @@ def api_post(
request.app.state.web_contract, route_path, body)
except TaskRunConflict as exc:
return _conflict(exc)
+ except UpdateBusy as exc:
+ return JSONResponse({'error': 'update in progress', 'message': str(exc)}, status_code=409)
except KeyError:
return JSONResponse({"error": "not found"}, status_code=404)
except RevisionConflict as exc:
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index 48ab4fcc5..d86b02de6 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -500,11 +500,6 @@ def download_update(request: Request, _args=Depends(require_auth)):
@router.post("/api/configuration/update-restart")
def restart_update(request: Request, _args=Depends(require_auth)):
local_only(request)
- contract = request.app.state.web_contract
- from .jobs import BackgroundJob
- if any(isinstance(job, BackgroundJob) and (job.snapshot() or {}).get("status") == "running"
- for job in vars(contract).values()):
- raise HTTPException(409, "后台任务正在运行,请完成后重启安装。")
try:
return standalone_update.request_restart()
except (ValueError, Timeout) as exc:
diff --git a/src/peach/standalone_update.py b/src/peach/standalone_update.py
index 3739383c6..57e8f1042 100644
--- a/src/peach/standalone_update.py
+++ b/src/peach/standalone_update.py
@@ -21,6 +21,7 @@ from filelock import FileLock, Timeout
from . import __version__, desktop_installer, distribution, release_updates, settings_file
from .fsutil import atomic_write_text
from .windows_update import replace_with_retry
+from . import update_tasks
ACTIVE = {"downloading", "verifying", "extracting", "preparing", "restarting", "installing"}
MAX_ARCHIVE = 512 * 1024 * 1024
@@ -173,7 +174,13 @@ def request_restart() -> dict:
data = read()
if data.get("state") != "ready":
raise ValueError("更新尚未准备完成")
- write(data, state="restarting", progress=0, message="正在重启安装")
+ db = settings_file.load_config().directory("database") / "ledger.db"
+ token = update_tasks.reserve(db)
+ try:
+ write(data, state="restarting", task_token=token, progress=0, message="正在保存任务进度,随后重启安装")
+ except Exception:
+ update_tasks.release(db, token)
+ raise
return public()
@@ -184,14 +191,22 @@ def poll(tray) -> None:
return
try:
data = read()
+ db = settings_file.load_config().directory("database") / "ledger.db"
+ token = data.get("task_token") or update_tasks.reserve(db)
+ if not data.get("task_token"):
+ write(data, task_token=token)
+ update_tasks.wait_quiescent(db)
helper = Path(data["helper"]) / "Peach.exe"
environment = os.environ.copy()
environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"
environment[settings_file.DATA_ROOT_ENV] = str(settings_file.load_config().data_root.resolve())
- subprocess.Popen([str(helper), "--apply-standalone-update", str(state_path()), str(os.getpid())],
+ process = subprocess.Popen([str(helper), "--apply-standalone-update", str(state_path()), str(os.getpid())],
cwd=str(helper.parent), env=environment, creationflags=subprocess.CREATE_NO_WINDOW)
+ update_tasks.transfer(db, token, process.pid)
tray.exit(reason="standalone-update")
except Exception as exc:
+ if 'token' in locals():
+ update_tasks.release(db, token)
write(read(), state="error", message=f"未能重启:{exc}")
finally:
tray._action_lock.release()
@@ -231,13 +246,10 @@ def restore_database(data: dict) -> None:
raise RuntimeError("数据库恢复检查失败")
-def apply(manifest: Path, wait_pid: int) -> int:
- """复制出来的助手等待原托盘正常退出,再在同一卷上切换两个目录。"""
- from .windows_restart import process_alive, start_tray, find_tray_windows, post_stop
- from .tray import configured_service_specs
- from .settings_file import load_config
+def _transaction_paths(manifest: Path):
+ """只接受本机状态文件与同卷暂存目录,安装目标须为完整独立包。"""
if manifest.resolve() != state_path().resolve():
- return 2
+ raise ValueError('更新状态文件不匹配')
data = read()
target = Path(data["target"]).resolve()
transaction = Path(data["transaction"]).resolve()
@@ -245,16 +257,41 @@ def apply(manifest: Path, wait_pid: int) -> int:
if (transaction.parent != target.parent or transaction.name != f".{target.name}-update-{data['id']}"
or stage != transaction / "stage" / "Peach" or state_path().resolve().is_relative_to(target)
or not (target / "_internal" / "standalone.txt").is_file()):
+ raise ValueError('更新目录无效')
+ return data, target, transaction, stage
+
+
+def apply(manifest: Path, wait_pid: int) -> int:
+ """复制出来的助手等待原托盘正常退出,再在同一卷上切换两个目录。"""
+ from .windows_restart import process_alive, start_tray, find_tray_windows, post_stop
+ from .tray import configured_service_specs
+ from .settings_file import load_config
+ from . import job_recovery
+ try:
+ data, target, transaction, stage = _transaction_paths(manifest)
+ except ValueError:
return 2
backup = transaction / "backup"
moved = False
installed = False
+ db = load_config().directory("database") / "ledger.db"
+ token = data.get("task_token")
+ previous = job_recovery.legacy_library_request(db)
+ try:
+ if token:
+ update_tasks.transfer(db, token, os.getpid())
+ else:
+ token = update_tasks.reserve(db)
+ except Exception as exc:
+ write(data, state="error", progress=0, message=f"安装预检未通过,程序与数据库未更改:{exc}")
+ return 1
try:
deadline = time.monotonic() + 90
while process_alive(wait_pid):
if time.monotonic() > deadline:
raise TimeoutError("托盘尚未退出,安装已取消")
time.sleep(.25)
+ job_recovery.import_legacy_library(db, previous)
migrate_database(stage, data)
write(data, state="installing", progress=20, message="正在保留旧版本")
replace_with_retry(target, backup)
@@ -263,6 +300,7 @@ def apply(manifest: Path, wait_pid: int) -> int:
replace_with_retry(stage, target)
installed = True
write(data, progress=80, message="正在启动新版本")
+ update_tasks.release(db, token)
start_tray(target / "Peach.exe")
deadline = time.monotonic() + 90
specs = configured_service_specs(load_config())
@@ -293,6 +331,7 @@ def apply(manifest: Path, wait_pid: int) -> int:
replace_with_retry(target, transaction / "failed")
replace_with_retry(backup, target)
restore_database(data)
+ update_tasks.release(db, token)
start_tray(target / "Peach.exe")
message = f"更新失败,已恢复旧版本:{exc}"
except Exception as rollback:
@@ -301,9 +340,14 @@ def apply(manifest: Path, wait_pid: int) -> int:
message = f"更新未安装:{exc}"
try:
restore_database(data)
+ if token:
+ update_tasks.release(db, token)
if not process_alive(wait_pid):
start_tray(target / "Peach.exe")
except Exception as rollback:
message = f"更新失败,数据库恢复未完成:{rollback}"
write(data, state="error", progress=0, message=message)
return 1
+ finally:
+ if token:
+ update_tasks.release(db, token)
diff --git a/src/peach/task_runs.py b/src/peach/task_runs.py
index d565ff84c..34f0d8c04 100644
--- a/src/peach/task_runs.py
+++ b/src/peach/task_runs.py
@@ -267,6 +267,38 @@ class TaskRunStore:
def start(self, task_key: str, *, trigger: str, mutex_key: str | None = None,
conflict: str = "skip", total: int | None = None,
label: str = "", pid: int | None = None) -> TaskRun | None:
+ from .update_tasks import admission
+ with admission(self.database.db_path):
+ from .job_recovery import current_run
+ resumed = self._resume(current_run.get(), task_key)
+ if resumed is not None:
+ return resumed
+ return self._start(task_key, trigger=trigger, mutex_key=mutex_key,
+ conflict=conflict, total=total, label=label, pid=pid)
+
+ def suspend(self, run_id: int) -> None:
+ if not self.enabled:
+ return
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute(
+ "UPDATE task_run SET status='pending',pid=0,progress_label=?,result_summary=? "
+ "WHERE id=? AND status='running'",
+ ('等待安装完成后继续', json.dumps({'paused_for_update': True}), run_id))
+
+ def _resume(self, run_id, task_key):
+ if run_id is None or not self.enabled:
+ return None
+ with self.database.write_transaction(notify=False) as connection:
+ cursor = connection.execute(
+ "UPDATE task_run SET status='running',pid=?,host=?,heartbeat_at=?,result_summary='{}' "
+ "WHERE id=? AND task_key=? AND status='pending' "
+ "AND json_extract(result_summary,'$.paused_for_update')=1",
+ (os.getpid(), self.host, stamp(), run_id, task_key))
+ return self.get(run_id) if cursor.rowcount else None
+
+ def _start(self, task_key: str, *, trigger: str, mutex_key: str | None = None,
+ conflict: str = "skip", total: int | None = None,
+ label: str = "", pid: int | None = None) -> TaskRun | None:
"""开一轮。互斥冲突时按 `conflict` 处理,返回 None 或抛 `TaskRunConflict`。
`conflict="skip"` 是定时触发的语义:本轮不跑,但要留下一条记录说明被谁挡了。
@@ -487,6 +519,14 @@ class TaskRunStore:
return int(cursor.lastrowid)
def claim_followup(self, task_keys) -> TaskRun | None:
+ from .update_tasks import admission, UpdateBusy
+ try:
+ with admission(self.database.db_path):
+ return self._claim_followup(task_keys)
+ except UpdateBusy:
+ return None
+
+ def _claim_followup(self, task_keys) -> TaskRun | None:
"""领走这几类里最早的一条待跑后继并标 `running`;没有就返回 None。
`task_keys` 是调用方这条通道负责的任务种类。按 id 升序领:后继之间没有优先级
@@ -583,6 +623,11 @@ class TaskRunStore:
for run in self.query(status="active", limit=1000):
if run.followup:
continue
+ if run.status == 'pending' and run.result_summary.get('paused_for_update'):
+ from .job_recovery import read
+ recovery = read(self.database.db_path, run.task_key)
+ if recovery.get('status') == 'active' and recovery.get('run_id') == run.id:
+ continue
local = run.host == self.host
alive = (local and run.pid is not None and run.pid != os.getpid()
and process_alive(run.pid))
diff --git a/src/peach/update_tasks.py b/src/peach/update_tasks.py
new file mode 100644
index 000000000..8bca53891
--- /dev/null
+++ b/src/peach/update_tasks.py
@@ -0,0 +1,208 @@
+"""同一数据目录内,任务起跑与安装准备共用进程间闸门。"""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+import json
+import os
+from pathlib import Path
+import socket
+import uuid
+import threading
+import time
+from weakref import WeakValueDictionary
+
+from filelock import FileLock, Timeout
+
+from .fsutil import atomic_write_text
+
+
+class UpdateBusy(ValueError):
+ """任务或安装事务占用数据目录,调用方应保留当前程序。"""
+
+
+def state_for(db: Path) -> Path:
+ parent = Path(db).resolve().parent
+ data = parent.parent if parent.name == "database" else parent
+ return data / "state" / "update-tasks"
+
+
+_locks = WeakValueDictionary()
+_locks_guard = threading.Lock()
+current_db = ContextVar('peach_task_database', default=None)
+
+
+def _mutex(root: Path) -> FileLock:
+ root.mkdir(parents=True, exist_ok=True)
+ with _locks_guard:
+ lock = _locks.get(root)
+ if lock is None:
+ lock = FileLock(root / "admission.lock", timeout=10)
+ _locks[root] = lock
+ return lock
+
+
+def _read(path: Path) -> dict:
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return {}
+ except (OSError, ValueError) as exc:
+ raise UpdateBusy("任务保护状态无法读取,请检查数据目录后重试。") from exc
+ if not isinstance(value, dict):
+ raise UpdateBusy("任务保护状态无效,请检查数据目录后重试。")
+ return value
+
+
+def _alive(data: dict) -> bool:
+ from .jobs import process_alive
+ pid = data.get("pid")
+ return isinstance(pid, int) and process_alive(pid)
+
+
+def _maintenance(root: Path) -> dict:
+ path = root / "install.json"
+ data = _read(path)
+ if data and not _alive(data):
+ path.unlink(missing_ok=True)
+ return {}
+ return data
+
+
+@contextmanager
+def admission(db: Path):
+ """持锁完成任务登记;安装取得预约后不接受新任务。"""
+ root = state_for(db)
+ with _mutex(root):
+ if _maintenance(root):
+ raise UpdateBusy("正在准备安装更新,暂时不能启动新任务。请等待安装完成。")
+ yield
+
+
+def register(db: Path, label: str) -> Path:
+ """登记线程任务或 CLI;文件在执行结束时撤下,死进程由预检回收。"""
+ with admission(db):
+ path = state_for(db) / "active" / (uuid.uuid4().hex + ".json")
+ atomic_write_text(path, json.dumps({"pid": os.getpid(), "label": label}, ensure_ascii=False))
+ return path
+
+
+@contextmanager
+def activity(db: Path, label: str):
+ path = register(db, label)
+ context = current_db.set(Path(db))
+ try:
+ yield
+ finally:
+ current_db.reset(context)
+ path.unlink(missing_ok=True)
+
+
+def reserve(db: Path, *, owner: int | None = None) -> str:
+ """接受安装预约并通知所有服务保存进度、暂停任务。"""
+ root = state_for(db)
+ with _mutex(root):
+ if _maintenance(root):
+ raise UpdateBusy("已有更新安装正在进行,请等待完成。")
+ token = uuid.uuid4().hex
+ atomic_write_text(root / "install.json", json.dumps({
+ "pid": owner if owner is not None else os.getpid(), "token": token}))
+ from .job_recovery import request_pause
+ request_pause(db)
+ return token
+
+
+def is_pausing(db: Path) -> bool:
+ root = state_for(db)
+ with _mutex(root):
+ return bool(_maintenance(root))
+
+
+def check_pause(db: Path | None) -> None:
+ if db is not None and is_pausing(db):
+ from .jobs import JobPaused
+ raise JobPaused('任务已暂停,安装完成后自动继续。')
+
+
+def _running(db: Path) -> list[str]:
+ from .jobs import process_alive
+ from .runtime_prepare import task_gate
+ root = state_for(db)
+ with _mutex(root):
+ labels = []
+ for path in (root / "active").glob("*.json"):
+ data = _read(path)
+ if _alive(data):
+ labels.append(str(data.get("label") or "后台任务"))
+ else:
+ path.unlink(missing_ok=True)
+ gate = task_gate(db, host=socket.gethostname(), alive=process_alive)
+ if gate.error:
+ labels.append('任务状态未取得')
+ labels.extend(run.describe() for run in (*gate.blocking, *gate.resumable)
+ if run.status == "running" and (run.pid is None or process_alive(run.pid)))
+ # 旧版 CLI 已有 PID 锁,预检同时兼容这些仍在运行的批次。
+ legacy = [root.parent / name for name in ('.probe.lock', '.sheets.lock', '.creator-boards.lock')]
+ for path in legacy:
+ if not path.exists():
+ continue
+ try:
+ pid = int(path.read_text(encoding="ascii").strip())
+ except (OSError, ValueError):
+ raise UpdateBusy("批处理进程状态无法确认,安装已取消。") from None
+ paused = _read(root / 'paused' / f'{pid}.json')
+ if process_alive(pid) and not paused:
+ labels.append(path.stem)
+ library_lock = root.parent / 'library-processing.json.lock'
+ try:
+ with FileLock(library_lock, timeout=0):
+ pass
+ except Timeout:
+ labels.append('馆藏资料与预览处理')
+ return list(dict.fromkeys(labels))
+
+
+def wait_quiescent(db: Path, timeout: float = 30) -> bool:
+ """等在途步骤保存进度;期限到后由安装入口停止自己拥有的服务。"""
+ deadline = time.monotonic() + timeout
+ while _running(db):
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(.1)
+ return True
+
+
+def wait_for_installation(db: Path) -> None:
+ """源码批处理保留 PID 锁,在安装期间暂停,结束后由原进程接着执行。"""
+ path = state_for(db) / 'paused' / f'{os.getpid()}.json'
+ atomic_write_text(path, json.dumps({'pid': os.getpid()}))
+ try:
+ while is_pausing(db):
+ time.sleep(.25)
+ finally:
+ path.unlink(missing_ok=True)
+
+
+def transfer(db: Path, token: str, owner: int) -> None:
+ """把安装预约交给更新助手或安装器,避免托盘退出产生空档。"""
+ root = state_for(db)
+ with _mutex(root):
+ data = _read(root / "install.json")
+ if not token or data.get("token") != token:
+ raise UpdateBusy("更新安装预约已失效,请重新准备更新。")
+ atomic_write_text(root / "install.json", json.dumps({"pid": owner, "token": token}))
+
+
+def release(db: Path, token: str) -> None:
+ root = state_for(db)
+ with _mutex(root):
+ if _read(root / "install.json").get("token") == token:
+ (root / "install.json").unlink(missing_ok=True)
+
+
+def release_owner(db: Path, owner: int) -> None:
+ root = state_for(db)
+ with _mutex(root):
+ data = _read(root / 'install.json')
+ if data.get('pid') == owner:
+ release(db, data['token'])
diff --git a/src/peach/web_feeds.py b/src/peach/web_feeds.py
index 9043dd5b1..dec162814 100644
--- a/src/peach/web_feeds.py
+++ b/src/peach/web_feeds.py
@@ -223,9 +223,10 @@ def w_feed_check(contract, body) -> dict:
started = contract.feed_job.start(
work, restart=True,
trigger="scheduled" if body.get("automatic") else "manual",
+ recovery={**{key: body[key] for key in ('sources', 'all', 'automatic') if key in body}, 'background': True},
initial={"ok": True, "checked": 0, "total": 0, "results": [], "added": 0,
"request_id": request_id, "current": None})
- if body.get("background"):
+ if body.get("background") or started.get('waiting_for_update'):
return started
if started["request_id"] != request_id:
return {"ok": False, "busy": True, "checked": 0, "results": []}
diff --git a/src/peach/web_follow.py b/src/peach/web_follow.py
index 24a0f0fb5..e8436fa6f 100644
--- a/src/peach/web_follow.py
+++ b/src/peach/web_follow.py
@@ -2041,9 +2041,11 @@ def w_follow_check(contract, body) -> dict:
# 轮询撞上在跑的那一轮记成跳过,手动撞上外部占用则由 API 回 409。
started = contract.follow_job.start(work, restart=True,
trigger="scheduled" if body.get("automatic") else "manual",
+ recovery={**{key: body[key] for key in ('source', 'sources', 'older', 'backfill_all', 'automatic') if key in body},
+ 'background': True},
initial={"ok": True, "checked": 0, "total": 0, "results": [],
"request_id": request_id, "older": bool(body.get("older")), "current": None})
- if body.get("background"):
+ if body.get("background") or started.get('waiting_for_update'):
return started
if started["request_id"] != request_id:
return {"ok": False, "busy": True, "checked": 0, "results": []}
@@ -2055,6 +2057,9 @@ def w_follow_check(contract, body) -> dict:
if worker is not None and worker is not threading.current_thread():
worker.join(5)
if "error" in outcome:
+ from .jobs import JobPaused
+ if isinstance(outcome['error'], JobPaused):
+ return contract.follow_job.snapshot() or started
raise outcome["error"]
return outcome["result"]
diff --git a/src/peach/web_job_recovery.py b/src/peach/web_job_recovery.py
new file mode 100644
index 000000000..7ef418330
--- /dev/null
+++ b/src/peach/web_job_recovery.py
@@ -0,0 +1,45 @@
+"""Web 组合入口为可恢复任务装配领域处理器。"""
+from .job_recovery import resume
+from .web_library_processing import w_library_processing
+from .web_scraping import w_scraping_cover
+from .web_timeline_thumbnails import w_thumbnail_jobs
+from .web_follow import w_follow_check
+from .web_feeds import w_feed_check
+from .web_wants import start_scrape
+from apscheduler.schedulers.background import BackgroundScheduler
+
+
+def restore(contract):
+ return resume(contract.db_path, {
+ "library-processing": lambda body: w_library_processing(contract, body, resume=True),
+ "timeline-thumbnails": lambda body: w_thumbnail_jobs(contract, body),
+ "scraping-cover": lambda body: w_scraping_cover(contract, body),
+ "follow-check": lambda body: w_follow_check(contract, body),
+ "feed-check": lambda body: w_feed_check(contract, body),
+ "want-scrape": lambda _body: start_scrape(contract),
+ })
+
+
+class RecoveryService:
+ """安装取消或完成后,现有服务也会接回等待中的任务。"""
+
+ def __init__(self, contract, *, available):
+ self.contract = contract
+ self.available = available
+ self.scheduler = BackgroundScheduler()
+
+ def start(self):
+ if self.available and not self.scheduler.running:
+ self.scheduler.add_job(self.tick, 'interval', seconds=1,
+ max_instances=1, coalesce=True)
+ self.scheduler.start()
+
+ def stop(self):
+ if self.scheduler.running:
+ self.scheduler.shutdown(wait=True)
+
+ def tick(self):
+ from .update_tasks import is_pausing
+ if not is_pausing(self.contract.db_path):
+ restore(self.contract)
+ self.contract.followups.resume_after_update()
diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.py
index dd447a054..33ea0aa64 100644
--- a/src/peach/web_library_processing.py
+++ b/src/peach/web_library_processing.py
@@ -14,6 +14,10 @@ def _current(contract):
def q_library_processing(contract, _args):
state = decorate(_current(contract))
+ from .job_recovery import read
+ recovery = read(contract.db_path, 'library-processing')
+ if state.get('status') != 'running' and recovery.get('status') == 'blocked':
+ state.update(status='failed', error=f"任务未能自动恢复:{recovery.get('error') or '请重新发起任务'}")
# 上一趟任务的状态文件里没有这个字段,而它那份完整清单还在磁盘上:按 job_id
# 推出地址补回去,界面才有得可给。
if state.get('issue_count') and state.get('job_id') and not state.get('issues_log'):
@@ -67,7 +71,7 @@ def _retry_ids(previous, body):
return chosen
-def w_library_processing(contract, body):
+def w_library_processing(contract, body, *, resume=False):
config = settings_file.active()
if not config.configured or not config.locations:
raise ValueError('请先添加媒体文件夹')
@@ -95,6 +99,7 @@ def w_library_processing(contract, body):
# 自动落库与页面写的是同一个 `LedgerDatabase`:进程内写锁在实例上,
# 另建一个就是在同一个进程里开第二条写入路径。
database=contract.database,
+ resume_state=previous if resume else None,
active=lambda: (contract.library_processing_job.snapshot() or {}).get('job_id') == job_id,
report=lambda state: contract.library_processing_job.update(job_id, **{
key: value for key, value in state.items() if key != 'job_id'}))
@@ -106,4 +111,6 @@ def w_library_processing(contract, body):
labels = {ALL_STAGES: '准备处理', SCAN_STAGE: '准备扫描文件', COLLECT_STAGE: '准备采集资料',
METADATA_STAGE: '准备采集资料', PREVIEWS_STAGE: '准备生成预览图'}
return contract.library_processing_job.start(
- work, restart=True, initial={'stage': labels[stage], 'requested_stage': stage})
+ work, restart=True, initial={'stage': labels[stage], 'requested_stage': stage},
+ recovery={'stage': stage, **({'asset_ids': asset_ids or retry_ids}
+ if asset_ids is not None or retry_ids is not None else {})})
diff --git a/src/peach/web_scraping.py b/src/peach/web_scraping.py
index c94094340..d053d577a 100644
--- a/src/peach/web_scraping.py
+++ b/src/peach/web_scraping.py
@@ -48,7 +48,7 @@ def w_scraping_cover(contract, body):
with contract.database.read_connection() as connection:
if not connection.execute("SELECT 1 FROM asset WHERE code=? LIMIT 1", (code,)).fetchone():
raise ValueError("馆藏未找到这个番号")
- return contract.scraping_cover_job.start_result(lambda: _fetch_cover(contract, code))
+ return contract.scraping_cover_job.start_result(lambda: _fetch_cover(contract, code), recovery={'code': code})
def _unavailable_reason(exc, network_failed: bool, statuses: set[int]) -> tuple[str, str]:
diff --git a/src/peach/web_timeline_thumbnails.py b/src/peach/web_timeline_thumbnails.py
index 9308e1248..c1718d116 100644
--- a/src/peach/web_timeline_thumbnails.py
+++ b/src/peach/web_timeline_thumbnails.py
@@ -58,6 +58,9 @@ def q_thumbnail_jobs(contract, _args):
return {'mode': read_mode(), 'modes': list(timeline_sheets.MODES),
'intervals': dict(timeline_sheets.INTERVALS),
'status': state.get('status') or 'idle',
+ 'stage': state.get('stage') or '',
+ 'message': state.get('message') or '',
+ 'waiting_for_update': bool(state.get('waiting_for_update')),
'job_id': state.get('job_id') or '',
'total': state.get('total') or 0, 'done': state.get('done') or 0,
'made': state.get('made') or 0, 'skipped': state.get('skipped') or 0,
@@ -77,7 +80,7 @@ def w_thumbnail_jobs(contract, body):
raise ValueError('采集密度无效')
write_mode(mode)
if mode == timeline_sheets.OFF:
- contract.thumbnail_job.stop()
+ contract.thumbnail_job.stop(resume=False)
return q_thumbnail_jobs(contract, {})
choice = FFmpegResolver(FFMPEG_DIR).ffmpeg()
if choice is None:
@@ -101,7 +104,7 @@ def w_thumbnail_jobs(contract, body):
status='failed' if failed else 'complete',
error=stopped if failed else '')
- contract.thumbnail_job.start(work, restart=True,
+ contract.thumbnail_job.start(work, restart=True, recovery={'mode': mode},
initial={'mode': mode, 'interval': interval,
'stage': '采集缩略图', 'checked': 0,
'total': 0, 'done': 0, 'made': 0,
diff --git a/src/peach/web_wants.py b/src/peach/web_wants.py
index a06280f43..2c3376c0c 100644
--- a/src/peach/web_wants.py
+++ b/src/peach/web_wants.py
@@ -128,7 +128,7 @@ def start_scrape(contract, *, trigger: str = "manual") -> dict | None:
contract.want_job.update(job_id, **result, status="complete", current=None,
completed_at=time.time())
try:
- return contract.want_job.start(work, restart=True, trigger=trigger,
+ return contract.want_job.start(work, restart=True, trigger=trigger, recovery={},
initial={"ok": True, "checked": 0, "total": 0, "current": None})
except TaskRunConflict:
# 另一个进程占着这把互斥键:登记已经落库,资料留给下一轮。
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 770004fe6..7bb1c3f80 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -3219,6 +3219,73 @@ class UnconfiguredMachineTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(app.state.follow_scheduler._started)
self.assertFalse(app.state.web_contract.feed_scheduler._started)
+ async def test_service_startup_replays_an_interrupted_library_request_with_its_scope(self):
+ from peach import job_recovery, settings_file
+ parent = self.settings.db_path.parent
+ parent.mkdir(parents=True)
+ database = fresh_ledger(parent)
+ job_recovery.save(database, 'library-processing', 'interrupted', {'stage': 'previews'})
+ path = parent.parent / 'state/job-recovery/library-processing.json'
+ record = json.loads(path.read_text(encoding='utf-8'))
+ record['pid'] = -1
+ path.write_text(json.dumps(record), encoding='utf-8')
+ media = parent.parent / 'media'
+ media.mkdir()
+ config = replace(settings_file.load_config(environ={'PEACH_DATA_ROOT': str(parent.parent)}),
+ present=True, locations={'local': (str(media),)})
+ invoked = threading.Event()
+ def process(*_args, **kwargs):
+ self.assertEqual(kwargs['stage'], 'previews')
+ invoked.set()
+ return {'status': 'complete'}
+ with patch('peach.settings_file.active', return_value=config), patch(
+ 'peach.web_library_processing.process_library', side_effect=process):
+ async with self.ledger_client(database) as (app, _client):
+ self.assertTrue(await asyncio.to_thread(invoked.wait, 5))
+ thread = app.state.web_contract.library_processing_job.thread
+ await asyncio.to_thread(thread.join, 5)
+ self.assertEqual(job_recovery.read(database, 'library-processing')['status'], 'complete')
+
+ async def test_cancelled_installation_resumes_the_paused_task_in_the_existing_service(self):
+ from peach import job_recovery, settings_file, update_tasks
+ parent = self.settings.db_path.parent
+ parent.mkdir(parents=True)
+ database = fresh_ledger(parent)
+ media = parent.parent / 'media'
+ media.mkdir()
+ config = replace(settings_file.load_config(environ={'PEACH_DATA_ROOT': str(parent.parent)}),
+ present=True, locations={'local': (str(media),)})
+ entered, checkpoint, completed = threading.Event(), threading.Event(), threading.Event()
+ calls = []
+ def process(*_args, **kwargs):
+ calls.append(kwargs['stage'])
+ entered.set()
+ checkpoint.wait(5)
+ kwargs['report']({'stage': '生成预览图'})
+ completed.set()
+ return {'status': 'complete'}
+ with patch('peach.settings_file.active', return_value=config), patch(
+ 'peach.web_library_processing.process_library', side_effect=process):
+ async with self.ledger_client(database) as (app, _client):
+ from peach.web_library_processing import w_library_processing
+ job = app.state.web_contract.library_processing_job
+ w_library_processing(app.state.web_contract, {'stage': 'previews'})
+ self.assertTrue(await asyncio.to_thread(entered.wait, 5))
+ run_id = job.snapshot()['run_id']
+ token = update_tasks.reserve(database)
+ try:
+ checkpoint.set()
+ await asyncio.to_thread(job.thread.join, 5)
+ self.assertTrue(job.snapshot()['waiting_for_update'])
+ self.assertEqual(app.state.web_contract.task_runs.get(run_id).status, 'pending')
+ finally:
+ update_tasks.release(database, token)
+ checkpoint.set()
+ self.assertTrue(await asyncio.to_thread(completed.wait, 5))
+ await asyncio.to_thread(job.thread.join, 5)
+ self.assertEqual(calls, ['previews', 'previews'])
+ self.assertEqual(job.snapshot()['run_id'], run_id)
+
async def test_preparing_the_ledger_requires_a_service_restart_to_resume_background_work(self):
parent = self.settings.db_path.parent
parent.mkdir(parents=True)
diff --git a/tests/test_follow_scheduler.py b/tests/test_follow_scheduler.py
index 71cceb55e..f29f64057 100644
--- a/tests/test_follow_scheduler.py
+++ b/tests/test_follow_scheduler.py
@@ -31,6 +31,19 @@ class FollowScheduleStoreTests(unittest.TestCase):
class FollowUpdateSchedulerTests(unittest.TestCase):
+ def test_installation_reservation_skips_the_tick_without_recording_a_failure(self):
+ from peach.update_tasks import UpdateBusy
+ def blocked():
+ raise UpdateBusy('正在安装')
+ with tempfile.TemporaryDirectory() as temporary:
+ scheduler = FollowUpdateScheduler(Path(temporary), blocked, available=True)
+ with self.assertNoLogs('peach', level='ERROR'):
+ scheduler._run()
+ status = scheduler.status()
+ self.assertEqual(status['consecutive_failures'], 0)
+ self.assertIsNone(status['last_error'])
+ self.assertIsNotNone(status['last_skipped_at'])
+
def test_interval_job_waits_one_interval_and_can_be_disabled(self):
with tempfile.TemporaryDirectory() as temporary:
scheduler = FollowUpdateScheduler(Path(temporary), lambda: {"ok": True}, available=True)
diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.py
index 20afef5b6..adb51d7ad 100644
--- a/tests/test_metadata_library.py
+++ b/tests/test_metadata_library.py
@@ -237,6 +237,7 @@ class LibraryNfoTests(unittest.TestCase):
from peach.web_library_processing import q_library_processing
from unittest.mock import patch
contract = Mock()
+ contract.db_path = self.root / 'database/ledger.db'
contract.library_processing_job.snapshot.return_value = {'status': 'running', 'job_id': 'one'}
with patch('peach.web_library_processing.process_library') as worker:
self.assertEqual(q_library_processing(contract, {})['job_id'], 'one')
@@ -1893,6 +1894,7 @@ class LibraryWatchdogTests(unittest.TestCase):
state_path(config).write_text(json.dumps({'status': 'failed', 'job_id': 'old', 'issue_count': 1}),
encoding='utf-8')
contract = Mock()
+ contract.db_path = self.root / 'database/ledger.db'
contract.library_processing_job.snapshot.return_value = None
with patch('peach.web_library_processing.settings_file.active', return_value=config):
self.assertEqual(q_library_processing(contract, {})['issues_log'], str(log))
@@ -2182,7 +2184,7 @@ class LibraryWatchdogTests(unittest.TestCase):
cache_bust=lambda: None, database=Mock(),
library_processing_job=SimpleNamespace(
snapshot=lambda: None,
- start=lambda work, restart, initial: (work('job'), initial)[1],
+ start=lambda work, restart, initial, recovery: (work('job'), initial)[1],
update=lambda job_id, **values: None))
media = self.root / 'media'
media.mkdir()
@@ -2388,7 +2390,7 @@ class LibraryPreviewCompletionTests(unittest.TestCase):
previous = {'job_id': 'old', 'status': 'failed', 'requested_stage': 'previews',
'retryable_asset_ids': [1]}
job = SimpleNamespace(snapshot=lambda: None, update=lambda *_args, **_kwargs: None,
- start=lambda work, restart, initial: (work('new'), initial)[1])
+ start=lambda work, restart, initial, recovery: (work('new'), initial)[1])
contract = SimpleNamespace(db_path=self.db, database=self.database,
candidate_root=self.root / 'candidates', cover_root=self.root / 'covers',
library_processing_job=job, cache_bust=lambda: None)
@@ -2405,6 +2407,33 @@ class LibraryPreviewCompletionTests(unittest.TestCase):
with self.subTest(selection=selection), self.assertRaises(ValueError):
w_library_processing(contract, {'asset_ids': selection})
+ def test_preview_checkpoint_restarts_only_unfinished_movies(self):
+ from peach import library_processing
+ with self.database.write_transaction() as connection:
+ video = self.media / 'clip-5.mp4'
+ video.write_bytes(b'video')
+ connection.execute(
+ "INSERT INTO asset(id,location,path,name,medium,duration) VALUES(5,'local',?,?, 'video',30)",
+ (str(video), video.name))
+ seen = []
+ def capture(_config, row, _database, _resolver, *, progress):
+ seen.append(row['id'])
+ progress()
+ if row['id'] == 5:
+ raise InterruptedError('模拟服务退出')
+ return True
+ with patch.object(library_processing, '_generate_preview', side_effect=capture):
+ with self.assertRaises(InterruptedError):
+ self.run_processing(stage='previews', asset_ids=[1, 5])
+ saved = snapshot(self.config)
+ self.assertEqual(saved['completed_previews'], [f'1:{self.media / "clip-1.mp4"}'])
+ seen.clear()
+ with patch.object(library_processing, '_generate_preview',
+ side_effect=lambda _c, row, *_a, **_k: seen.append(row['id']) or True):
+ result = self.run_processing(stage='previews', asset_ids=[1, 5], resume_state=saved)
+ self.assertEqual(seen, [5])
+ self.assertEqual(result['status'], 'complete')
+
def test_real_local_video_produces_a_snapshot_and_card_poster(self):
import subprocess
from peach.ffmpeg import FFmpegResolver
diff --git a/tests/test_standalone_update.py b/tests/test_standalone_update.py
index 0767eeafd..fa1daebcc 100644
--- a/tests/test_standalone_update.py
+++ b/tests/test_standalone_update.py
@@ -61,6 +61,7 @@ class StandaloneUpdateTests(unittest.TestCase):
with patch.object(update.settings_file, "load_config", return_value=selected), patch.object(
update.distribution, "standalone", return_value=True), patch.object(update.subprocess, "Popen") as launch:
update.write({"helper": str(self.root / "helper")}, state="restarting")
+ launch.return_value.pid = os.getpid()
update.poll(tray)
self.assertEqual(launch.call_args.args[0][2], str(selected.directory("state") / "standalone-update.json"))
self.assertEqual(launch.call_args.kwargs["env"]["PEACH_DATA_ROOT"], str(selected.data_root))
@@ -108,6 +109,20 @@ class StandaloneUpdateTests(unittest.TestCase):
with self.assertRaises(ValueError):
update.start()
+ def test_restart_accepts_running_tasks_and_requests_their_pause(self):
+ from peach.task_runs import TaskRunStore
+ from support.ledger import fresh_ledger
+ fresh_ledger(self.database.parent)
+ store = TaskRunStore(self.database)
+ run = store.start('library-processing', trigger='scheduled')
+ update.write({}, state='ready', version='1.0.0')
+ with patch.object(update.distribution, 'standalone', return_value=True), patch.object(update.sys, 'platform', 'win32'):
+ self.assertEqual(update.request_restart()['state'], 'restarting')
+ self.assertTrue(update.update_tasks.is_pausing(self.database))
+ with self.assertRaisesRegex(ValueError, '安装更新'):
+ store.start('timeline-thumbnails', trigger='manual')
+ update.update_tasks.release(self.database, update.read()['task_token'])
+
def test_download_prepares_verified_package_without_stopping_the_app(self):
target = self.root / "installed"; target.mkdir()
(target / "Peach.exe").write_text("old")
diff --git a/tests/test_update_tasks.py b/tests/test_update_tasks.py
new file mode 100644
index 000000000..82c8a5437
--- /dev/null
+++ b/tests/test_update_tasks.py
@@ -0,0 +1,266 @@
+"""升级预检以真实临时账本、进程与文件锁验证任务保护和恢复。"""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+from unittest.mock import patch
+
+from peach import desktop_installer, job_recovery, settings_file, update_tasks
+from peach.jobs import BackgroundJob
+from peach.task_runs import TaskRunStore
+from support.ledger import fresh_ledger
+
+
+class UpdateTaskTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name).resolve()
+ self.db = self.root / 'database/ledger.db'
+ self.db.parent.mkdir()
+ fresh_ledger(self.db.parent)
+ self.store = TaskRunStore(self.db)
+
+ def test_running_tasks_receive_a_pause_request_when_installation_is_accepted(self):
+ for trigger in ('manual', 'scheduled'):
+ with self.subTest(trigger=trigger):
+ run = TaskRunStore(self.db).start('library-processing', trigger=trigger)
+ token = update_tasks.reserve(self.db)
+ self.assertTrue(update_tasks.is_pausing(self.db))
+ self.assertFalse(update_tasks.wait_quiescent(self.db, timeout=0))
+ self.store.finish(run.id, 'succeeded')
+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=0))
+ update_tasks.release(self.db, token)
+
+ def test_reservation_prevents_task_start_until_release(self):
+ token = update_tasks.reserve(self.db)
+ with self.assertRaises(update_tasks.UpdateBusy):
+ self.store.start('timeline-thumbnails', trigger='manual')
+ job = BackgroundJob('test', runs=self.store, task_key='library-processing')
+ called = threading.Event()
+ state = job.start(lambda _: called.set(), recovery={'stage': 'previews'})
+ self.assertFalse(called.is_set())
+ self.assertTrue(state['waiting_for_update'])
+ self.assertEqual(job_recovery.read(self.db, 'library-processing')['request'], {'stage': 'previews'})
+ update_tasks.release(self.db, token)
+ self.assertIsNotNone(self.store.start('timeline-thumbnails', trigger='manual'))
+
+ def test_checkpoint_pause_and_resume_keep_the_same_task_run(self):
+ entered, progress = threading.Event(), threading.Event()
+ job = BackgroundJob('test', runs=self.store, task_key='library-processing')
+ attempts = []
+ def work(job_id):
+ attempts.append(job_id)
+ entered.set()
+ progress.wait(5)
+ job.update(job_id, status='complete')
+ job.start(work, recovery={'stage': 'previews'})
+ self.assertTrue(entered.wait(5))
+ run_id = job.snapshot()['run_id']
+ token = update_tasks.reserve(self.db)
+ progress.set()
+ job.thread.join(5)
+ self.assertFalse(job.thread.is_alive())
+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=0))
+ self.assertEqual(self.store.get(run_id).status, 'pending')
+ self.assertEqual(self.store.recover_interrupted(), [])
+ self.assertTrue(job.snapshot()['waiting_for_update'])
+ update_tasks.release(self.db, token)
+ resumed = job_recovery.resume(self.db, {'library-processing':
+ lambda body: job.start(work, restart=True, recovery=body)})
+ self.assertEqual(resumed, ['library-processing'])
+ job.thread.join(5)
+ self.assertEqual(len(attempts), 2)
+ self.assertEqual(attempts[0], attempts[1])
+ self.assertEqual(job.snapshot()['run_id'], run_id)
+ self.assertEqual(self.store.get(run_id).status, 'succeeded')
+
+ def test_installation_pause_is_reconciled_when_the_service_exits_during_a_step(self):
+ run = self.store.start('library-processing', trigger='manual', pid=-1)
+ job_recovery.save(self.db, 'library-processing', 'old', {'stage': 'previews'}, run_id=run.id)
+ token = update_tasks.reserve(self.db)
+ path = update_tasks.state_for(self.db).parent / 'job-recovery/library-processing.json'
+ data = json.loads(path.read_text(encoding='utf-8'))
+ data['pid'] = -1
+ path.write_text(json.dumps(data), encoding='utf-8')
+ job_recovery.reconcile_paused(self.db)
+ self.assertEqual(self.store.get(run.id).status, 'pending')
+ self.assertEqual(self.store.recover_interrupted(), [])
+ update_tasks.release(self.db, token)
+
+ def test_another_service_cannot_replace_the_scope_already_waiting_for_installation(self):
+ token = update_tasks.reserve(self.db)
+ first = BackgroundJob('one', runs=self.store, task_key='library-processing')
+ second = BackgroundJob('two', runs=TaskRunStore(self.db), task_key='library-processing')
+ original = first.start(lambda _: None, recovery={'stage': 'previews', 'asset_ids': [7]})
+ later = second.start(lambda _: None, recovery={'stage': 'metadata', 'asset_ids': [9]})
+ self.assertEqual(original['job_id'], later['job_id'])
+ self.assertEqual(job_recovery.read(self.db, 'library-processing')['request'],
+ {'stage': 'previews', 'asset_ids': [7]})
+ update_tasks.release(self.db, token)
+
+ def test_source_batch_waits_for_installation_and_continues_in_the_same_process(self):
+ import argparse
+ from peach.jobs import DiskGuard, job_main
+ entered, checkpoint = threading.Event(), threading.Event()
+ lock = self.root / 'state/.probe.lock'
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--lock', default=lock, type=Path)
+ parser.add_argument('--db', default=self.db, type=Path)
+ attempts, results = [], []
+ def run(_args):
+ guard = DiskGuard(self.root, 0)
+ attempts.append(os.getpid())
+ entered.set()
+ checkpoint.wait(5)
+ guard.check()
+ return 0
+ thread = threading.Thread(target=lambda: results.append(job_main(lambda: parser, run, [])))
+ thread.start()
+ try:
+ self.assertTrue(entered.wait(5))
+ token = update_tasks.reserve(self.db)
+ checkpoint.set()
+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=5))
+ self.assertTrue(thread.is_alive())
+ update_tasks.release(self.db, token)
+ finally:
+ checkpoint.set()
+ update_tasks.release_owner(self.db, os.getpid())
+ thread.join(10)
+ self.assertEqual(results, [0])
+ self.assertEqual(attempts, [os.getpid(), os.getpid()])
+
+ def test_a_live_thread_remains_protected_after_its_record_is_cancelled(self):
+ entered, release = threading.Event(), threading.Event()
+ job = BackgroundJob('test', runs=self.store, task_key='library-processing')
+ def work(_):
+ entered.set()
+ release.wait(10)
+ job.start(work)
+ thread = job.thread
+ try:
+ self.assertTrue(entered.wait(5))
+ job.stop(timeout=0)
+ token = update_tasks.reserve(self.db)
+ self.assertFalse(update_tasks.wait_quiescent(self.db, timeout=0))
+ finally:
+ release.set()
+ thread.join(10)
+ self.assertFalse(thread.is_alive())
+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=0))
+ update_tasks.release(self.db, token)
+
+ def child(self, source):
+ child = subprocess.Popen([sys.executable, '-X', 'utf8', '-c', source, str(self.db)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, encoding='utf-8')
+ def cleanup():
+ if child.poll() is None:
+ child.kill()
+ child.communicate(timeout=10)
+ self.addCleanup(cleanup)
+ return child
+
+ def test_cli_activity_is_observed_without_refusing_the_installation_request(self):
+ child = self.child("from pathlib import Path; import sys; "
+ "from peach.update_tasks import register; "
+ "register(Path(sys.argv[1]), 'CLI 抽帧'); print('ready', flush=True); input()")
+ self.assertEqual(child.stdout.readline().strip(), 'ready')
+ token = update_tasks.reserve(self.db)
+ self.assertFalse(update_tasks.wait_quiescent(self.db, timeout=0))
+ child.kill()
+ child.communicate(timeout=10)
+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=0))
+ update_tasks.release(self.db, token)
+
+ def test_installer_accepts_a_running_task_and_holds_the_pause_until_completion(self):
+ config = settings_file.load_config(environ={'PEACH_DATA_ROOT': str(self.root)})
+ run = self.store.start('library-processing', trigger='manual')
+ error = self.root / 'prepare-error.txt'
+ with patch.object(settings_file, 'load_config', return_value=config), patch.object(
+ desktop_installer, 'stop', return_value=True) as stop, patch.object(
+ update_tasks, 'wait_quiescent', return_value=False):
+ self.assertEqual(desktop_installer.prepare(self.root / 'app', os.getpid(), error), 0)
+ stop.assert_called_once()
+ self.assertFalse(error.exists())
+ with self.assertRaises(update_tasks.UpdateBusy):
+ self.store.start('timeline-thumbnails', trigger='manual')
+ desktop_installer.finish_install(self.root / 'app', os.getpid())
+ self.assertIsNotNone(self.store.start('timeline-thumbnails', trigger='manual'))
+
+ def test_unreadable_task_state_keeps_the_database_bytes_for_the_installer_diagnostic(self):
+ self.db.write_bytes(b'not sqlite')
+ token = update_tasks.reserve(self.db)
+ self.assertFalse(update_tasks.wait_quiescent(self.db, timeout=0))
+ self.assertEqual(self.db.read_bytes(), b'not sqlite')
+ update_tasks.release(self.db, token)
+
+ def test_installer_migration_uses_the_selected_data_directory_and_skips_empty_installs(self):
+ config = settings_file.load_config(environ={'PEACH_DATA_ROOT': str(self.root)})
+ with patch.object(settings_file, 'load_config', return_value=config), patch(
+ 'peach.cli.main', return_value=0) as migrate:
+ self.assertEqual(desktop_installer.migrate_install(self.root / 'app'), 0)
+ migrate.assert_called_once_with(['migrate', 'upgrade', '--yes', '--db', str(self.db)])
+ migrate.reset_mock()
+ self.db.unlink()
+ self.assertEqual(desktop_installer.migrate_install(self.root / 'app'), 0)
+ migrate.assert_not_called()
+ self.assertFalse(self.db.exists())
+
+ def test_installer_owner_handoff_does_not_allow_new_tasks_between_processes(self):
+ token = update_tasks.reserve(self.db)
+ child = self.child('print("ready", flush=True); input()')
+ self.assertEqual(child.stdout.readline().strip(), 'ready')
+ update_tasks.transfer(self.db, token, child.pid)
+ update_tasks.release(self.db, 'wrong-token')
+ with self.assertRaises(update_tasks.UpdateBusy):
+ self.store.start('library-processing', trigger='manual')
+ child.kill()
+ child.communicate(timeout=10)
+ self.assertIsNotNone(self.store.start('library-processing', trigger='manual'))
+
+ def test_interrupted_task_request_is_replayed_once_by_two_service_instances(self):
+ child = self.child("from pathlib import Path; import sys; from peach.job_recovery import save; "
+ "save(Path(sys.argv[1]), 'library-processing', 'old', "
+ "{'stage':'previews','asset_ids':[7,9]}); print('ready', flush=True); input()")
+ self.assertEqual(child.stdout.readline().strip(), 'ready')
+ calls = []
+ def replay(body):
+ calls.append(body)
+ job_recovery.save(self.db, 'library-processing', 'new', body)
+ handlers = {'library-processing': replay}
+ self.assertEqual(job_recovery.resume(self.db, handlers), [])
+ child.kill()
+ child.communicate(timeout=10)
+ self.assertEqual(job_recovery.resume(self.db, handlers), ['library-processing'])
+ self.assertEqual(job_recovery.resume(self.db, handlers), [])
+ self.assertEqual(calls, [{'stage': 'previews', 'asset_ids': [7, 9]}])
+
+ def test_completed_failed_and_explicitly_cancelled_requests_are_not_replayed(self):
+ for status in ('complete', 'failed'):
+ job_recovery.save(self.db, 'library-processing', 'a', {'stage': 'collect'})
+ job_recovery.finish(self.db, 'library-processing', 'a', status)
+ self.assertEqual(job_recovery.read(self.db, 'library-processing')['status'], status)
+ job_recovery.cancel(self.db, 'library-processing')
+ self.assertEqual(job_recovery.read(self.db, 'library-processing'), {})
+
+ def test_a_stale_request_validation_failure_is_visible_without_an_automatic_retry_loop(self):
+ job_recovery.save(self.db, 'library-processing', 'old', {'asset_ids': [404]})
+ path = update_tasks.state_for(self.db).parent / 'job-recovery/library-processing.json'
+ data = json.loads(path.read_text(encoding='utf-8'))
+ data['pid'] = -1
+ path.write_text(json.dumps(data), encoding='utf-8')
+ calls = []
+ def fail(body):
+ calls.append(body)
+ raise ValueError('影片已移出馆藏')
+ with self.assertLogs('peach.job_recovery', level='WARNING'):
+ self.assertEqual(job_recovery.resume(self.db, {'library-processing': fail}), [])
+ self.assertEqual(job_recovery.read(self.db, 'library-processing')['status'], 'blocked')
+ self.assertEqual(job_recovery.resume(self.db, {'library-processing': fail}), [])
+ self.assertEqual(len(calls), 1)
diff --git a/tests/test_web_timeline_thumbnails.py b/tests/test_web_timeline_thumbnails.py
index e0e0bd0ef..1c0684f42 100644
--- a/tests/test_web_timeline_thumbnails.py
+++ b/tests/test_web_timeline_thumbnails.py
@@ -56,7 +56,7 @@ class ThumbnailJobEndpointTests(unittest.TestCase):
made.parent.mkdir(parents=True)
made.write_bytes(b"sheet")
state = web_timeline_thumbnails.w_thumbnail_jobs(self.contract, {"mode": "off"})
- self.contract.thumbnail_job.stop.assert_called_once_with()
+ self.contract.thumbnail_job.stop.assert_called_once_with(resume=False)
self.assertEqual(state["mode"], "off")
self.assertTrue(made.is_file())