Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: harden contract errors and transaction lifecycle

longmeidaob2a2e23917b7
diff --git a/src/peach/api.py b/src/peach/api.py
index 746945251..3155ce5b4 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -38,6 +38,9 @@ from .sync import LedgerSync
from .transcodes import TranscodeService, TranscodeUnavailable
+LOGGER = logging.getLogger(__name__)
+
+
def _first_query_values(request: Request) -> dict[str, str]:
"""兼容 urllib.parse.parse_qs:取首值并忽略空值。"""
result: dict[str, str] = {}
@@ -560,8 +563,9 @@ def create_app(
return JSONResponse({"error": "not found"}, status_code=404)
except (TypeError, ValueError) as exc:
return JSONResponse({"error": f"{type(exc).__name__}: {exc}"}, status_code=400)
- except Exception as exc:
- return JSONResponse({"error": f"{type(exc).__name__}: {exc}"}, status_code=500)
+ except Exception:
+ LOGGER.exception("unhandled GET contract error for /api/%s", route)
+ return JSONResponse({"error": "internal server error"}, status_code=500)
@app.post("/api/{route:path}")
def api_post(route: str, request: Request, body: dict[str, Any] = Body(default_factory=dict)):
@@ -579,7 +583,8 @@ def create_app(
return JSONResponse({"error": "not found"}, status_code=404)
except (TypeError, ValueError) as exc:
return JSONResponse({"error": f"{type(exc).__name__}: {exc}"}, status_code=400)
- except Exception as exc:
- return JSONResponse({"error": f"{type(exc).__name__}: {exc}"}, status_code=500)
+ except Exception:
+ LOGGER.exception("unhandled POST contract error for /api/%s", route)
+ return JSONResponse({"error": "internal server error"}, status_code=500)
return app
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 0531bfb37..85990d4e8 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -376,12 +376,16 @@ def build_macos_service_specs() -> tuple[ServiceSpec, ...]:
return tuple(specs)
-def build_service_specs(lan_address: str | None = None) -> tuple[ServiceSpec, ...]:
+def build_service_specs(
+ lan_address: str | None = None,
+ *,
+ tls_dir: Path | None = None,
+) -> tuple[ServiceSpec, ...]:
if sys.platform == "darwin":
return build_macos_service_specs()
address = lan_address or os.environ.get("PEACH_LAN_ADDRESS", DEFAULT_LAN_ADDRESS)
peach = str(_peach_executable())
- cert_dir = SECRETS_DIR / "tls"
+ cert_dir = Path(tls_dir) if tls_dir is not None else SECRETS_DIR / "tls"
ca = cert_dir / "peach-local-ca.crt"
cert = cert_dir / "peach.crt"
key = cert_dir / "peach.key"
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 2a826c784..59d97286d 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -14,6 +14,7 @@ import re
import sqlite3
import threading
import time
+from contextlib import contextmanager
from pathlib import Path
from typing import Sequence
from urllib.parse import quote, urlsplit
@@ -165,6 +166,34 @@ class WebContract:
connection.create_function("is_jav_code", 1, is_jav_code, deterministic=True)
return connection
+ @contextmanager
+ def read_connection(self):
+ """Yield one read-only connection and always close it.
+
+ ``sqlite3.Connection`` only commits or rolls back when used as a context
+ manager; it does not close itself. Keep the lifecycle rule in one place.
+ """
+ connection = self.db()
+ try:
+ yield connection
+ finally:
+ connection.close()
+
+ @contextmanager
+ def write_transaction(self):
+ """Serialize one write transaction, roll it back on failure, then close."""
+ with self.write_lock:
+ connection = self.db(write=True)
+ try:
+ yield connection
+ except BaseException:
+ connection.rollback()
+ raise
+ else:
+ connection.commit()
+ finally:
+ connection.close()
+
def has_snapshot(self, raw_path: str | None) -> bool:
if not raw_path:
return False
@@ -457,21 +486,17 @@ def w_search_history(contract: WebContract, body):
if operation == "remove":
if not query:
raise ValueError("query is required")
- with contract.write_lock:
- connection = contract.db(write=True)
+ with contract.write_transaction() as connection:
connection.execute("DELETE FROM search_history WHERE query=?", (query,))
- connection.commit(); connection.close()
return {"ok": True, "operation": operation}
if operation != "remember" or not query or len(query) > 200:
raise ValueError("invalid search history request")
- with contract.write_lock:
- connection = contract.db(write=True)
+ with contract.write_transaction() as connection:
connection.execute(
"INSERT INTO search_history(query,used_count,last_used_at) VALUES(?,1,datetime('now')) "
"ON CONFLICT(query) DO UPDATE SET used_count=used_count+1,last_used_at=excluded.last_used_at",
(query,),
)
- connection.commit(); connection.close()
return {"ok": True, "operation": operation}
@@ -1339,8 +1364,7 @@ def w_review_decision(contract: WebContract, body):
raise ValueError("invalid review decision")
now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
note = str(body.get("note", "")).strip()[:2000]
- with contract.write_lock:
- connection = contract.db(write=True)
+ with contract.write_transaction() as connection:
connection.execute(
"INSERT INTO review_decision(category,item_key,status,note,updated_at) VALUES(?,?,?,?,?) "
"ON CONFLICT(category,item_key) DO UPDATE SET status=excluded.status,note=excluded.note,updated_at=excluded.updated_at",
@@ -1350,14 +1374,9 @@ def w_review_decision(contract: WebContract, body):
if category == "metadata_fields" and status == "approved":
candidate_key = str(body.get("candidate_key") or "").strip()
if not candidate_key:
- connection.rollback(); connection.close()
raise ValueError("批准字段候选时必须选择一个来源值")
group, candidate = _selected_metadata_candidate(contract, item_key, candidate_key)
- try:
- applied = _apply_metadata_candidate(connection, group, candidate, now)
- except Exception:
- connection.rollback(); connection.close()
- raise
+ applied = _apply_metadata_candidate(connection, group, candidate, now)
provenance_note = json.dumps({
"candidate_key": candidate_key, "source": candidate.get("source"),
"user_note": note,
@@ -1373,20 +1392,16 @@ def w_review_decision(contract: WebContract, body):
for row in read_candidates(category, contract.candidate_root)[0]}
candidate = candidates.get(item_key)
if candidate is None:
- connection.rollback(); connection.close()
raise ValueError("候选不在当前批次,无法批准")
if str(candidate.get("status") or "").strip() != "candidate":
- connection.rollback(); connection.close()
raise ValueError("只有 candidate 状态的复核项可以批准")
creator = str(candidate.get("creator") or "").strip()
tags = [tag.strip() for tag in str(candidate.get("tags") or "").split("|") if tag.strip()]
claimed_creator = str(body.get("creator", "")).strip()
claimed_tags = [tag.strip() for tag in str(body.get("tags", "")).split("|") if tag.strip()]
if (claimed_creator and claimed_creator != creator) or (claimed_tags and claimed_tags != tags):
- connection.rollback(); connection.close()
raise ValueError("提交内容与候选不一致,拒绝写入")
if not creator or not tags:
- connection.rollback(); connection.close()
raise ValueError("approved creator review requires creator and tags")
entity = connection.execute(
"SELECT e.id FROM entity e LEFT JOIN entity_alias a ON a.entity_id=e.id "
@@ -1394,7 +1409,6 @@ def w_review_decision(contract: WebContract, body):
(creator, creator),
).fetchone()
if not entity:
- connection.rollback(); connection.close()
raise ValueError("creator entity not found")
assets = connection.execute(
"SELECT DISTINCT ae.asset_id FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
@@ -1405,7 +1419,6 @@ def w_review_decision(contract: WebContract, body):
available_ids = {asset["asset_id"] for asset in assets}
if selected_ids:
if not selected_ids <= available_ids:
- connection.rollback(); connection.close()
raise ValueError("selected assets are outside the reviewed creator")
asset_ids = sorted(selected_ids)
else:
@@ -1413,7 +1426,6 @@ def w_review_decision(contract: WebContract, body):
# 却照样把决定记成 approved——留痕说通过、实际没写是最糟的组合。
asset_ids = sorted(available_ids)
if len(asset_ids) > REVIEW_APPLY_LIMIT:
- connection.rollback(); connection.close()
raise ValueError(
f"该创作者有 {len(asset_ids)} 条作品,超过单次批准上限 "
f"{REVIEW_APPLY_LIMIT},请在页面上显式勾选后再通过"
@@ -1448,7 +1460,6 @@ def w_review_decision(contract: WebContract, body):
[(asset_id, entity_id, payload, now, now) for asset_id in asset_ids],
)
applied = len(asset_ids)
- connection.commit(); connection.close()
contract.cache_bust() # 标签写完,聚合缓存必须失效,否则 facets 最多 90 秒还是旧数
return {"ok": True, "category": category, "item_key": item_key, "status": status, "applied_assets": applied}
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 89f715b24..dd4019f4c 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -363,6 +363,18 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
{"k": "横屏", "n": 1},
])
+ async def test_unexpected_contract_errors_are_logged_but_not_exposed(self):
+ with patch(
+ "peach.api.web_contract.dispatch_api_get",
+ side_effect=RuntimeError("private C:\\ledger.db detail"),
+ ):
+ with self.assertLogs("peach.api", level="ERROR") as captured:
+ response = await self.client.get("/api/items?t=secret")
+ self.assertEqual(response.status_code, 500)
+ self.assertEqual(response.json(), {"error": "internal server error"})
+ self.assertNotIn("ledger.db", response.text)
+ self.assertIn("private C:\\ledger.db detail", "\n".join(captured.output))
+
async def test_preference_is_an_independent_authenticated_write(self):
denied = await self.client.post(
"/api/preference", json={"id": 1, "liked": True, "reason": "镜头自然"},
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 67d24a884..21d7070af 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -323,6 +323,25 @@ class WebDataTests(unittest.TestCase):
self.assertEqual(self.contract.cached("same", lambda: "first"), "first")
self.assertEqual(other.cached("same", lambda: "second"), "second")
+ def test_write_transaction_rolls_back_and_closes_on_failure(self):
+ opened = []
+ real_db = self.contract.db
+
+ def capture(write=False):
+ connection = real_db(write)
+ opened.append(connection)
+ return connection
+
+ with mock.patch.object(self.contract, "db", side_effect=capture):
+ with self.assertRaisesRegex(RuntimeError, "abort"):
+ with self.contract.write_transaction() as connection:
+ connection.execute("UPDATE asset SET name='changed' WHERE id=1")
+ raise RuntimeError("abort")
+
+ self.assertEqual(self.row(1)["name"], "one.mp4")
+ with self.assertRaises(sqlite3.ProgrammingError):
+ opened[0].execute("SELECT 1")
+
def test_item_tag_add_and_remove_preserve_source_evidence(self):
added = rm_web.w_item_tag(self.contract, {
"id": 1, "operation": "add", "tag": "新标签",
diff --git a/tests/test_tray.py b/tests/test_tray.py
index 767fd8562..952ccf3d8 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -51,7 +51,11 @@ class TrayTests(unittest.TestCase):
def test_services_never_own_ledger_sync(self):
"""浏览服务只观察写入角色;跨机复制只能由托盘显式执行。"""
- specs = build_service_specs()
+ with tempfile.TemporaryDirectory() as directory:
+ tls_dir = Path(directory)
+ for name in ("peach-local-ca.crt", "peach.crt", "peach.key"):
+ (tls_dir / name).write_text("test-only", encoding="utf-8")
+ specs = build_service_specs(tls_dir=tls_dir)
owners = [spec for spec in specs if "--no-ledger-sync" not in spec.command]
self.assertEqual(owners, [])
for spec in specs: