Peach: Local-first video metadata scraper and media manager.
fix(cli): peach process 结算时把声明的后继派进任务中心
longmeidao95f5cb5a4426
diff --git a/src/peach/cli.py b/src/peach/cli.pyindex 4a2262764..6063a48d7 100644--- a/src/peach/cli.py+++ b/src/peach/cli.py@@ -490,15 +490,30 @@ def _scan(args: argparse.Namespace) -> int:def _process_library(args: argparse.Namespace) -> int:+ """命令行跑资料处理,和网页那一轮一样记进任务中心、结算时派发声明的后继。++ 后继写成 `pending` 行,由服务的后继通道执行:服务下次派发后继或重启时会领走。+ """from .library_processing import process_libraryfrom .repository import LedgerDatabase+ from .task_runs import cli_run, declared_rows_require_readable_settings()config = settings_file.active()- result = process_library(config, args.db, config.directory('generated'),- config.directory('generated') / 'covers', location=args.location,- database=LedgerDatabase(args.db),- report=lambda state: print(f"{state['stage']}:{state['checked']}/{state['total']}", flush=True))- return 0 if result['status'] == 'complete' else 1+ with cli_run('library-processing', args.db, label='资料处理') as handle:+ result = process_library(config, args.db, config.directory('generated'),+ config.directory('generated') / 'covers', location=args.location,+ database=LedgerDatabase(args.db),+ report=lambda state: print(f"{state['stage']}:{state['checked']}/{state['total']}", flush=True))+ rows = declared_rows(result.get('followups'))+ queued = handle.store.enqueue_followups(handle.run_id, rows)+ if rows:+ print(f"后继:声明 {len(rows)} 条,入队 {len(queued['queued'])} 条,"+ f"已在排队 {queued['duplicates']} 条", flush=True)+ complete = result['status'] == 'complete'+ handle.finish('succeeded' if complete else 'failed',+ summary={'followups': len(queued['queued'])},+ error='' if complete else str(result.get('error') or '资料处理未完成'))+ return 0 if complete else 1def _create_data_tree(config: settings_file.PeachConfig) -> None:diff --git a/src/peach/jobs.py b/src/peach/jobs.pyindex cf1bca1fe..955af5c01 100644--- a/src/peach/jobs.py+++ b/src/peach/jobs.py@@ -526,12 +526,12 @@ class BackgroundJob:看这一轮有没有声明,中途中断的轮次声明不到。没入队的三种情况各占摘要里的一行——静默丢弃和没有上限一样,事后都查不出来。"""- declared = state.get("followups")+ from .task_runs import declared_rows+run_id = self._run_ids.get(job_id)- if self.runs is None or run_id is None or not isinstance(declared, list):+ if self.runs is None or run_id is None:return {}- rows = [(item.get("key"), item.get("task_key"), item.get("label", ""))- for item in declared if isinstance(item, dict) and item.get("key")]+ rows = declared_rows(state.get("followups"))if not rows:return {}result = self.runs.enqueue_followups(run_id, rows)diff --git a/src/peach/task_runs.py b/src/peach/task_runs.pyindex bd8973d32..c75911444 100644--- a/src/peach/task_runs.py+++ b/src/peach/task_runs.py@@ -705,6 +705,18 @@ def cli_run(task_key: str, db_path: Path | str | None, *, label: str = "",yield handle+def declared_rows(declared) -> list[tuple[str, str, str]]:+ """任务结果里声明的后继(`[{"key", "task_key", "label"}]`)换成 `enqueue_followups` 要的行。++ 后台任务的结算与命令行入口共用这一份:任务结果是同一个函数给的,两边各拆一遍,+ 命令行那边漏掉,就是一整轮新登记的女优全都没人去补头像和资料。+ """+ if not isinstance(declared, list):+ return []+ return [(item.get("key"), item.get("task_key"), item.get("label", ""))+ for item in declared if isinstance(item, dict) and item.get("key")]++@dataclassclass TaskRunHandle:"""一轮任务的句柄。`run_id is None` 表示这一轮没有被记录,所有方法都是空操作。"""diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 77a47402a..406e7d77c 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -522,6 +522,54 @@ class ScanCommandTests(unittest.TestCase):self.assertIn("peach init", output)+class ProcessCommandTests(unittest.TestCase):+ """`peach process` 和网页那一轮同一个处理函数,结算也要一样:声明的后继进任务中心。"""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.db = Path(self.tmp.name).resolve() / "ledger.db"+ upgrade(self.db, MIGRATIONS)+ config = settings_file.load_config(environ={}, strict=False)+ for target in (mock.patch.object(settings_file, "active", lambda: config),+ mock.patch.object(cli, "SETTINGS_ERROR", None)):+ target.start()+ self.addCleanup(target.stop)++ def _run(self, result):+ output = io.StringIO()+ with mock.patch("peach.library_processing.process_library", return_value=result), \+ redirect_stdout(output):+ code = cli.main(["process", "--db", str(self.db)])+ connection = sqlite3.connect(self.db)+ try:+ rows = connection.execute(+ "SELECT id,task_key,trigger,status,parent_run_id,followup_key FROM task_run "+ "ORDER BY id").fetchall()+ finally:+ connection.close()+ return code, output.getvalue(), rows++ def test_the_followups_a_run_declares_are_queued_under_it(self):+ declared = [{"key": "performer-alias:9378", "task_key": "performer-alias",+ "label": "补女优别名:白川麻衣"}]+ code, output, rows = self._run({"status": "complete", "followups": declared})+ self.assertEqual(code, 0)+ parent, child = rows+ self.assertEqual(parent[1:4], ("library-processing", "cli", "succeeded"))+ self.assertEqual(child[1:], ("performer-alias", "cli", "pending", parent[0],+ "performer-alias:9378"))+ self.assertIn("入队 1 条", output)++ def test_an_unfinished_run_is_recorded_as_failed_and_still_queues_its_followups(self):+ declared = [{"key": "performer-alias:1", "task_key": "performer-alias", "label": ""}]+ code, _, rows = self._run({"status": "failed", "error": "网盘离线",+ "followups": declared})+ self.assertEqual(code, 1)+ self.assertEqual(rows[0][3], "failed")+ self.assertEqual(rows[1][3], "pending")++class ReplicationAssemblyTests(unittest.TestCase):"""ADR-0023 第 3 阶段:整条复制链路按 `replication.enabled` 装配或完全不装配。"""