Peach: Local-first video metadata scraper and media manager.
fix(web): 链接清理改走 write_transaction,并给域契约加一致性门槛
longmeidao083cee1f26c0
diff --git a/src/peach/web_links.py b/src/peach/web_links.pyindex 68f3952cc..0e1a894ef 100644--- a/src/peach/web_links.py+++ b/src/peach/web_links.py@@ -40,7 +40,7 @@ class LinkContract(Protocol):def read_connection(self): ...- def write_connection(self): ...+ def write_transaction(self): ...def _probe(url: str, timeout: float = CHECK_TIMEOUT) -> tuple[int, str]:@@ -210,10 +210,11 @@ def w_links_prune(contract: LinkContract, body):removed = 0if confirmed:- with contract.write_connection() as connection:+ # 整批删除走同一个写事务:要么这一次判定的 gone 全部落库,要么一条都不落。+ with contract.write_transaction() as connection:for item in confirmed:- connection.execute("DELETE FROM entity_link WHERE id=?", (item["id"],))- removed += connection.execute("SELECT changes()").fetchone()[0]+ removed += connection.execute(+ "DELETE FROM entity_link WHERE id=?", (item["id"],)).rowcountwith contract.link_check_lock:state = contract.link_check_stateif state is not None and state["check_id"] == body.get("check_id"):diff --git a/tests/test_module_layering.py b/tests/test_module_layering.pyindex 8023b4095..14062bb56 100644--- a/tests/test_module_layering.py+++ b/tests/test_module_layering.py@@ -9,10 +9,14 @@ import 一个叫 web 的模块,读代码的人只会得出「分层反了」但名字骗人和结构错了一样难查。改名之后加这条断言,让下一次真反了的时候直接报错。"""import ast+import importlibimport pathlib+import tempfile+import typingimport unittestimport peach+from peach.web_contract import WebContractSOURCE_ROOT = pathlib.Path(peach.__file__).parent@@ -130,6 +134,53 @@ class SharedRuleTests(unittest.TestCase):"纯规则请直接从 peach.catalog_rules 取")+class ContractConformanceTests(unittest.TestCase):+ """域模块声明的窄契约,真的 `WebContract` 必须全部满足。++ `Protocol` 在运行期什么都不检查,域模块又只照着自己那份 Protocol 写调用,+ 于是「契约上写了、实现里没有」不会有任何东西报错,一路要等到用户点那个按钮。++ 实测事故:`web_links.LinkContract` 声明了 `write_connection`,`WebContract` 只有+ `write_transaction`,`/api/links/prune` 在线上直接 500;而 `tests/test_web_links.py`+ 的 FakeContract 恰好把两个名字都给了,测试因此全绿。这条门槛就是补那次的窗口。+ """++ @staticmethod+ def _declared(protocol) -> set[str]:+ """一份 Protocol 声明的能力:带注解的属性 + 协议体里定义的方法。"""+ names = set(typing.get_type_hints(protocol))+ names.update(name for name, value in vars(protocol).items()+ if callable(value) and not name.startswith("_"))+ return names++ @staticmethod+ def _web_protocols() -> list[type]:+ """web 层各模块自己定义的 Protocol,按文件名发现而不是手写清单。"""+ found: list[type] = []+ for path in sorted(SOURCE_ROOT.glob("web_*.py")):+ module = importlib.import_module(f"peach.{path.stem}")+ for obj in vars(module).values():+ if (isinstance(obj, type) and getattr(obj, "_is_protocol", False)+ and obj.__module__ == module.__name__ and obj not in found):+ found.append(obj)+ return found++ def test_every_web_protocol_is_satisfied_by_the_real_contract(self):+ protocols = self._web_protocols()+ self.assertGreaterEqual(len(protocols), 5, "没发现域契约,门槛已空转")+ with tempfile.TemporaryDirectory() as tmp:+ # 构造只是赋值路径和建锁,不碰磁盘也不连库;临时目录仅用于坐实这一点。+ contract = WebContract(pathlib.Path(tmp).resolve() / "ledger.db")+ missing = [f"{protocol.__name__}.{name}"+ for protocol in protocols+ for name in sorted(self._declared(protocol))+ if not hasattr(contract, name)]+ self.assertEqual(+ missing, [],+ "域契约声明了 WebContract 没有的能力:要么补上实现,要么改契约声明",+ )++class LayeringTests(unittest.TestCase):def test_the_web_layer_is_actually_discovered(self):"""推导出来的 web 层不能是空的。diff --git a/tests/test_web_links.py b/tests/test_web_links.pyindex 34e026e2b..bb41d9542 100644--- a/tests/test_web_links.py+++ b/tests/test_web_links.py@@ -20,6 +20,15 @@ CREATE TABLE entity_link(class FakeContract:+ """只提供 `LinkContract` 声明的那几项能力,且读写分开。++ 早先这里把 `read_connection` 和 `write_connection` 指向同一个可写函数,于是+ `w_links_prune` 调了真契约上根本不存在的 `write_connection` 也照样绿——真的+ `WebContract` 只有 `read_connection` 与 `write_transaction`,线上删链接直接 500。+ 读连接因此按真实实现开成 SQLite 的 `mode=ro`:拿读连接写库会当场报错,而不是+ 悄悄成功。+ """+def __init__(self, db: Path):self.db_path = dbself.link_check_lock = threading.Lock()@@ -27,18 +36,29 @@ class FakeContract:self.link_check_thread = None@contextmanager- def _connect(self):+ def read_connection(self):+ connection = sqlite3.connect(+ self.db_path.resolve().as_uri() + "?mode=ro", uri=True)+ connection.row_factory = sqlite3.Row+ try:+ yield connection+ finally:+ connection.close()++ @contextmanager+ def write_transaction(self):connection = sqlite3.connect(self.db_path)connection.row_factory = sqlite3.Rowtry:yield connection+ except BaseException:+ connection.rollback()+ raise+ else:connection.commit()finally:connection.close()- read_connection = _connect- write_connection = _connect-class VerdictTests(unittest.TestCase):def test_only_a_gone_status_is_deletable(self):