Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(core): 后台任务与原子落盘各收成一份实现

longmeidao2d9b31dad1b7
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 24161fd5a..9917646ab 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -46,6 +46,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_restart_windows_tray.py",
"test_versioning.py",
"test_windows_update.py", "test_certs.py", "test_config.py",
+ "test_fsutil.py",
"test_job_status.py", "test_jobs.py", "test_reference_updates.py",
"test_repo_hygiene.py",
"test_review_csv.py",
diff --git a/src/peach/api.py b/src/peach/api.py
index b4de86e12..736852977 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -249,6 +249,9 @@ def create_app(
yield
finally:
follow_scheduler.stop()
+ # 死链检查和资源对账的后台线程是 daemon,本来挡不住进程退出;这里显式收
+ # 一下,免得在途的那一轮在解释器拆卸期间还继续查库、往没人读的状态里写。
+ contract.stop_background_jobs()
if mdns is not None:
await asyncio.to_thread(mdns.stop)
if sync is not None:
diff --git a/src/peach/fsutil.py b/src/peach/fsutil.py
new file mode 100644
index 000000000..960d8df9c
--- /dev/null
+++ b/src/peach/fsutil.py
@@ -0,0 +1,75 @@
+"""落盘只有两种结果:旧内容或新内容,不会有半成品。
+
+这套「先写临时文件再 `os.replace`」的手法在库里被抄了十几遍,每一遍都在同一批细节上
+各自发挥:临时文件放哪、叫什么、失败了谁删。抄错任何一条的表现都不是报错,而是别的
+请求读到一张半张的图或一段截断的 JSON——比崩掉难查得多。所以这里只留一份实现。
+
+三条约束是这个模块存在的全部理由:
+
+1. 临时文件必须和目标**同目录**。`os.replace` 只在同一个卷上才是原子的,而 `tempfile`
+ 的默认目录经常在另一个盘(Windows 上尤其如此),跨卷会退化成拷贝。
+2. 临时文件名必须带随机段。两个线程同时生成同一个目标是常态(同一张封面被两个卡片
+ 同时请求),共用一个 `x.tmp` 会让其中一个删掉另一个正在写的文件。
+3. 扩展名必须沿用目标的。FFmpeg 和 PIL 都按输出文件的扩展名决定编码格式,把临时名写成
+ `x.tmp` 会让它们直接失败。
+"""
+from __future__ import annotations
+
+import os
+import uuid
+from collections.abc import Iterator
+from contextlib import contextmanager
+from pathlib import Path
+
+
+@contextmanager
+def atomic_path(target: Path | str, *, suffix: str | None = None) -> Iterator[Path]:
+ """产出一个同目录的临时路径;正常退出就原子替换 `target`,出错就把它删掉。
+
+ 给的是路径而不是文件句柄,因为一半的调用方是把这个路径交给 FFmpeg 或 PIL 去写,
+ 自己并不碰文件内容。`suffix` 默认沿用目标的扩展名,需要覆盖时(例如目标没有扩展名
+ 但工具要求有)再显式传。
+ """
+ destination = Path(target)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ tail = destination.suffix if suffix is None else suffix
+ temporary = destination.with_name(
+ f".{destination.name}.{uuid.uuid4().hex[:12]}.tmp{tail}")
+ try:
+ yield temporary
+ except BaseException:
+ temporary.unlink(missing_ok=True)
+ raise
+ try:
+ os.replace(temporary, destination)
+ except BaseException:
+ temporary.unlink(missing_ok=True)
+ raise
+
+
+def atomic_write_bytes(target: Path | str, data: bytes, *,
+ mode: int | None = None) -> Path:
+ """把 `data` 原子地写成 `target`。返回目标路径,方便接着链下去。"""
+ with atomic_path(target) as temporary:
+ temporary.write_bytes(data)
+ _restrict(temporary, mode)
+ return Path(target)
+
+
+def atomic_write_text(target: Path | str, text: str, *, encoding: str = "utf-8",
+ mode: int | None = None) -> Path:
+ """同上,但写文本。编码显式给默认值,避免落到平台默认编码上。"""
+ with atomic_path(target) as temporary:
+ temporary.write_text(text, encoding=encoding)
+ _restrict(temporary, mode)
+ return Path(target)
+
+
+def _restrict(path: Path, mode: int | None) -> None:
+ """在替换之前收紧权限位,这样目标从来没有一刻是宽权限的。
+
+ Windows 上跳过:那里的 `chmod` 只能翻只读位,真正管事的是 ACL,调用它除了产生
+ 一个「已经设过权限」的错觉之外没有任何作用。
+ """
+ if mode is not None and os.name != "nt":
+ path.chmod(mode)
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index 5cb3b4b70..2ccb82d4b 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -1,9 +1,14 @@
-"""Peach 批处理任务共享的安全与成本策略。"""
+"""Peach 批处理任务共享的安全与成本策略,以及服务内后台任务的状态机。"""
from __future__ import annotations
+import copy
import shutil
import os
+import threading
import time
+import uuid
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
@@ -196,6 +201,106 @@ class PidFileLock:
self.release()
+class BackgroundJob:
+ """服务里一次「点一下、后台跑、前端轮询」的任务:锁、状态和线程都在这里。
+
+ 死链检查和资源对账各写了一份逐字相同的这个形状:一把锁、一个带 uuid 的状态字典、
+ `status_only` 与 `restart` 两个开关、一个 daemon 线程,以及一个把异常翻成
+ `status="failed"` 的 except。共用的不只是形状,还有三条容易漏的约定:
+
+ 1. **状态里必须带任务 id,而且每次改状态前都要核对**。轮询期间用户可以按
+ `restart` 顶掉在跑的那一轮;被顶掉的线程如果还继续写状态,前端看到的就是
+ 新一轮的 id 配旧一轮的进度。
+ 2. **后台异常必须变成可轮询的状态**。只写日志的话,界面会永远停在「进行中」。
+ 3. **`thread.start()` 不能在锁里**。
+
+ `snapshot()` 返回深拷贝:域模块的公开投影(挑字段、`[dict(x) for x in ...]`)
+ 因此可以在锁外安全地算,不必让每个域都自己记得「投影要在锁里做」。状态只装
+ JSON 形态的数据,拷贝很便宜。
+ """
+
+ def __init__(self, name: str, *, id_key: str = "job_id"):
+ #: 线程名,出现在崩溃栈和进程视图里,所以取和端点一致的名字。
+ self.name = name
+ #: 状态字典里存任务 id 的键名。域模块的公开投影直接下发它,所以沿用各域原有的
+ #: 名字(`check_id`/`scan_id`)而不是统一改名——那是前端契约。
+ self.id_key = id_key
+ self.lock = threading.Lock()
+ self.state: dict | None = None
+ self.thread: threading.Thread | None = None
+
+ def snapshot(self) -> dict | None:
+ """当前状态的深拷贝;一次都没跑过返回 None。"""
+ with self.lock:
+ return copy.deepcopy(self.state) if self.state is not None else None
+
+ def update(self, job_id: str, **fields: object) -> bool:
+ """状态仍属于 `job_id` 时改字段;已经被顶掉就什么都不做并返回 False。"""
+ with self.editing(job_id) as state:
+ if state is None:
+ return False
+ state.update(fields)
+ return True
+
+ @contextmanager
+ def editing(self, job_id: str) -> Iterator[dict | None]:
+ """拿住锁产出仍属于 `job_id` 的状态;被顶掉则产出 None。
+
+ 进度是往列表里追加、给计数加一,不都是整字段替换,所以除了 `update` 还要
+ 有这个原地改的入口。
+ """
+ with self.lock:
+ state = self.state
+ yield state if state is not None and state[self.id_key] == job_id else None
+
+ def start(self, fn: Callable[[str], None], *, initial: dict | None = None,
+ restart: bool = False) -> dict:
+ """跑一轮,返回启动后(或原有)状态的深拷贝。
+
+ 已经在跑,或者已经有结果而调用方没要求 `restart`,都原样返回现状——重复点击
+ 不该把一轮跑到一半的检查丢掉。`fn` 收到本轮的任务 id,自己负责把 `status`
+ 推到 `complete`:完成时要落什么结果字段是域的事。
+ """
+ thread = None
+ with self.lock:
+ state = self.state
+ if state is None or (restart and state["status"] != "running"):
+ job_id = uuid.uuid4().hex
+ state = {self.id_key: job_id, "status": "running",
+ "started_at": time.time(), "error": "", **(initial or {})}
+ self.state = state
+ thread = threading.Thread(target=self._run, args=(fn, job_id),
+ daemon=True, name=self.name)
+ self.thread = thread
+ snapshot = copy.deepcopy(state)
+ if thread is not None:
+ thread.start()
+ return snapshot
+
+ def stop(self, timeout: float | None = 2.0) -> None:
+ """丢掉状态并等线程收工,用于服务关停。
+
+ 线程是 daemon,本来也挡不住进程退出;清状态的意义是让在途的 worker 下一次
+ 拿锁时发现自己已被顶掉,从而安静返回,而不是在解释器拆卸期间继续查库、
+ 往一个没人读的状态里写进度。等不到就不等——一次外部 HTTP 探测可以是十几秒,
+ 关停不该被它拖住。
+ """
+ with self.lock:
+ self.state = None
+ thread = self.thread
+ self.thread = None
+ if thread is not None and thread.is_alive():
+ thread.join(timeout)
+
+ def _run(self, fn: Callable[[str], None], job_id: str) -> None:
+ try:
+ fn(job_id)
+ except Exception as error: # 后台失败必须变成可轮询的状态,不能只留在日志里
+ self.update(job_id, status="failed",
+ error=f"{type(error).__name__}: {error}",
+ completed_at=time.time())
+
+
def job_main(build_parser, run, argv: list[str] | None = None) -> int:
"""长跑批处理脚本的统一入口收尾。
diff --git a/src/peach/previews.py b/src/peach/previews.py
index abe03478e..2e51e7c53 100644
--- a/src/peach/previews.py
+++ b/src/peach/previews.py
@@ -9,6 +9,7 @@ from pathlib import Path
from PIL import Image, ImageOps
from .ffmpeg import FFmpegResolver
+from .fsutil import atomic_path
from .media import remap_managed_path
from .repository import LedgerRepository
@@ -31,8 +32,9 @@ _GENERATE_LOCKS = tuple(threading.Lock() for _ in range(_LOCK_STRIPES))
def _generate_lock(destination: Path) -> threading.Lock:
"""按目标文件取锁:同一个目标一定拿同一把,不同目标大概率并行。
- 同一目标同一把锁是这里的正确性要求——两个线程同时生成同一个文件,
- `os.replace` 会互相覆盖,而其中一个的临时文件可能已经被删掉了。
+ 同一目标同一把锁,锁内再判一次文件是否已存在:两个线程同时请求同一张图时,
+ 第二个直接返回第一个的结果,而不是再跑一遍 FFmpeg。落盘本身的安全由
+ `fsutil.atomic_path` 负责,这把锁省的是重复的转码开销。
"""
return _GENERATE_LOCKS[hash(str(destination)) % _LOCK_STRIPES]
@@ -58,16 +60,15 @@ class PreviewService:
ffmpeg = self._ffmpeg()
col, row = cell % 3, cell // 3
self.poster_root.mkdir(parents=True, exist_ok=True)
- temporary = destination.with_name(destination.stem + ".tmp.jpg")
with _generate_lock(destination):
if destination.is_file():
return destination
- self._run([
- str(ffmpeg), "-y", "-v", "error", "-i", str(source),
- "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},scale='min(640,iw)':-2",
- "-q:v", "4", str(temporary),
- ])
- os.replace(temporary, destination)
+ with atomic_path(destination) as temporary:
+ self._run([
+ str(ffmpeg), "-y", "-v", "error", "-i", str(source),
+ "-vf", f"crop=iw/3:ih/3:iw/3*{col}:ih/3*{row},scale='min(640,iw)':-2",
+ "-q:v", "4", str(temporary),
+ ])
return destination
def avatar(self, asset_id: int) -> Path:
@@ -208,18 +209,15 @@ class PhotoThumbnailService:
if destination.is_file():
return destination
self.root.mkdir(parents=True, exist_ok=True)
- # 临时文件名带线程号:并发请求同一张图时各写各的,最后谁替换都是同一张。
- temporary = destination.with_name(
- f"{destination.stem}.{os.getpid()}.{threading.get_ident()}.tmp.jpg")
- try:
- with Image.open(source) as opened:
- image = ImageOps.exif_transpose(opened)
- if image.mode not in {"RGB", "L"}:
- image = image.convert("RGB")
- image.thumbnail((self.width, self.width * 8), Image.LANCZOS)
- image.save(temporary, "JPEG", quality=82, optimize=True)
- except (OSError, ValueError, Image.DecompressionBombError) as exc:
- temporary.unlink(missing_ok=True)
- raise PreviewUnavailable("photo thumbnail failed") from exc
- os.replace(temporary, destination)
+ # 并发请求同一张图时各写各的临时文件,最后谁替换都是同一张。
+ with atomic_path(destination) as temporary:
+ try:
+ with Image.open(source) as opened:
+ image = ImageOps.exif_transpose(opened)
+ if image.mode not in {"RGB", "L"}:
+ image = image.convert("RGB")
+ image.thumbnail((self.width, self.width * 8), Image.LANCZOS)
+ image.save(temporary, "JPEG", quality=82, optimize=True)
+ except (OSError, ValueError, Image.DecompressionBombError) as exc:
+ raise PreviewUnavailable("photo thumbnail failed") from exc
return destination
diff --git a/src/peach/review_mirror.py b/src/peach/review_mirror.py
index c8e35b68b..791cd6eff 100644
--- a/src/peach/review_mirror.py
+++ b/src/peach/review_mirror.py
@@ -9,11 +9,9 @@ from __future__ import annotations
import ipaddress
import json
import logging
-import os
import ssl
import subprocess
import sys
-import tempfile
import time
from copy import deepcopy
from datetime import datetime, timezone
@@ -21,6 +19,8 @@ from pathlib import Path
from urllib.parse import urljoin, urlparse
from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
+from .fsutil import atomic_write_text
+
MAX_REVIEW_BYTES = 8 * 1024 * 1024
REVIEW_CACHE_SECONDS = 20.0
@@ -236,25 +236,10 @@ class ReviewMirror:
return result
def _write_cache(self, payload: dict, fetched_at: str) -> None:
- self.cache_path.parent.mkdir(parents=True, exist_ok=True)
- body = json.dumps(
+ # 只给自己读:这份缓存里是复核队列的完整内容,不该跟着数据目录的默认权限走。
+ atomic_write_text(self.cache_path, json.dumps(
{"fetched_at": fetched_at, "payload": payload}, ensure_ascii=False,
- )
- temporary: Path | None = None
- try:
- with tempfile.NamedTemporaryFile(
- mode="w", encoding="utf-8", dir=self.cache_path.parent,
- prefix=self.cache_path.name + ".", suffix=".tmp", delete=False,
- ) as handle:
- handle.write(body)
- temporary = Path(handle.name)
- if os.name != "nt":
- temporary.chmod(0o600)
- os.replace(temporary, self.cache_path)
- temporary = None
- finally:
- if temporary is not None:
- temporary.unlink(missing_ok=True)
+ ), mode=0o600)
def _read_cache(self) -> dict | None:
try:
diff --git a/src/peach/sync.py b/src/peach/sync.py
index 8eff1804a..cb390cf46 100644
--- a/src/peach/sync.py
+++ b/src/peach/sync.py
@@ -32,6 +32,7 @@ from dataclasses import dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
+from .fsutil import atomic_write_text
from .platform import root_online
@@ -146,11 +147,7 @@ def write_marker(db_path: Path, marker: Marker, *, with_digest: bool = True) ->
digest=digest_database(db_path) if with_digest else "",
wal_size=wal_payload_size(db_path),
)
- target = marker_path(db_path)
- target.parent.mkdir(parents=True, exist_ok=True)
- temporary = target.with_name(target.name + ".tmp")
- temporary.write_text(marker.as_json(), encoding="utf-8")
- os.replace(temporary, target)
+ atomic_write_text(marker_path(db_path), marker.as_json())
return marker
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 6853ccac7..5c49a617c 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -34,6 +34,7 @@ from .entities import (
resolve_entity,
upsert_asset_entity,
)
+from .jobs import BackgroundJob
from .media import remap_managed_path
from .metadata_policy import SOURCE_SPECS
from .platform import (
@@ -202,12 +203,10 @@ class WebContract:
self.cache_generation = 0
self.follow_check_lock = threading.Lock()
self.follow_scheduler = None
- self.resource_scan_lock = threading.Lock()
- self.resource_scan_state: dict | None = None
- self.resource_scan_thread: threading.Thread | None = None
- self.link_check_lock = threading.Lock()
- self.link_check_state: dict | None = None
- self.link_check_thread: threading.Thread | None = None
+ # 两块后台任务的锁、状态和线程都归 BackgroundJob 管,契约上只留这两个字段。
+ # 任务 id 的键名沿用各自原有的名字:它随公开投影下发,是前端契约。
+ self.resource_scan = BackgroundJob("PeachResourceScanJob", id_key="scan_id")
+ self.link_check = BackgroundJob("PeachLinkCheckJob", id_key="check_id")
self._fts_available: bool | None = None
def cached(self, key, fn):
@@ -235,6 +234,14 @@ class WebContract:
self.cache[key] = (now, value)
return value
+ def stop_background_jobs(self) -> None:
+ """服务关停时丢掉后台任务状态并等线程收工。
+
+ 谁在跑归契约自己知道,`api` 的 lifespan 不该再列一遍任务清单。
+ """
+ self.resource_scan.stop()
+ self.link_check.stop()
+
def cache_bust(self):
with self.cache_lock:
self.cache.clear()
diff --git a/src/peach/web_links.py b/src/peach/web_links.py
index 0e1a894ef..d5ec6285f 100644
--- a/src/peach/web_links.py
+++ b/src/peach/web_links.py
@@ -13,15 +13,15 @@
from __future__ import annotations
import re
-import threading
import time
-import uuid
from pathlib import Path
from typing import Protocol
from urllib.parse import urlsplit
import httpx
+from .jobs import BackgroundJob
+
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/128.0 Safari/537.36")
#: 「这个页面没了」——只有上游明确这么说,才够格作为删除依据。
@@ -34,9 +34,7 @@ class LinkContract(Protocol):
"""链接管理需要契约提供的能力;比整个 WebContract 小得多。"""
db_path: Path
- link_check_lock: threading.Lock
- link_check_state: dict | None
- link_check_thread: threading.Thread | None
+ link_check: BackgroundJob
def read_connection(self): ...
@@ -114,76 +112,52 @@ def _check_public(state: dict) -> dict:
def _run_link_check(contract: LinkContract, check_id: str) -> None:
- try:
- with contract.read_connection() as connection:
- rows = [dict(row) for row in connection.execute(
- "SELECT l.id, l.link_kind, l.label, l.url, e.canonical_name AS entity "
- "FROM entity_link l JOIN entity e ON e.id=l.entity_id ORDER BY l.id")]
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is None or state["check_id"] != check_id:
- return
- state["total"] = len(rows)
- for row in rows:
- status, note = _probe(row["url"])
- verdict = link_verdict(status, note)
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is None or state["check_id"] != check_id:
- return # 被新的检查顶掉了,安静收工
- state["checked"] += 1
- if verdict != "ok":
- state["gone" if verdict == "gone" else "unclear"].append({
- "id": row["id"], "entity": row["entity"],
- "link_kind": row["link_kind"], "label": row["label"],
- "url": row["url"],
- "note": f"HTTP {status}" if status else f"取不到:{note}",
- })
- time.sleep(CHECK_INTERVAL)
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is not None and state["check_id"] == check_id:
- state.update(status="complete", completed_at=time.time())
- except Exception as error: # 后台失败必须变成可轮询的状态,不能只留在日志里
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is not None and state["check_id"] == check_id:
- state.update(status="failed", error=f"{type(error).__name__}: {error}",
- completed_at=time.time())
+ """逐条联网重验。异常由 `BackgroundJob` 翻成 `failed` 状态,这里不再自己接。"""
+ job = contract.link_check
+ with contract.read_connection() as connection:
+ rows = [dict(row) for row in connection.execute(
+ "SELECT l.id, l.link_kind, l.label, l.url, e.canonical_name AS entity "
+ "FROM entity_link l JOIN entity e ON e.id=l.entity_id ORDER BY l.id")]
+ with job.editing(check_id) as state:
+ if state is None:
+ return
+ state["total"] = len(rows)
+ for row in rows:
+ status, note = _probe(row["url"])
+ verdict = link_verdict(status, note)
+ with job.editing(check_id) as state:
+ if state is None:
+ return # 被新的检查顶掉了,安静收工
+ state["checked"] += 1
+ if verdict != "ok":
+ state["gone" if verdict == "gone" else "unclear"].append({
+ "id": row["id"], "entity": row["entity"],
+ "link_kind": row["link_kind"], "label": row["label"],
+ "url": row["url"],
+ "note": f"HTTP {status}" if status else f"取不到:{note}",
+ })
+ time.sleep(CHECK_INTERVAL)
+ job.update(check_id, status="complete", completed_at=time.time())
def w_links_check(contract: LinkContract, body=None):
"""开始(或查询)一次死链检查。
七百多条链接逐条联网要好几分钟,同步请求必然超时,所以和资源对账走同一套:
- 后台线程 + 可轮询状态。
+ `BackgroundJob` 的后台线程 + 可轮询状态。
"""
body = body or {}
if body.get("status_only") is True:
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is None:
- return {"ok": True, "status": "idle", "check_id": "", "checked": 0,
- "total": 0, "gone": [], "unclear": []}
- return _check_public(state)
-
- thread = None
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is not None and state["status"] == "running":
- return _check_public(state)
- if state is not None and body.get("restart") is not True:
- return _check_public(state)
- check_id = uuid.uuid4().hex
- state = {"check_id": check_id, "status": "running", "checked": 0, "total": 0,
- "gone": [], "unclear": [], "started_at": time.time(), "error": ""}
- contract.link_check_state = state
- thread = threading.Thread(target=_run_link_check, args=(contract, check_id),
- daemon=True, name="PeachLinkCheckJob")
- contract.link_check_thread = thread
- response = _check_public(state)
- thread.start()
- return response
+ state = contract.link_check.snapshot()
+ if state is None:
+ return {"ok": True, "status": "idle", "check_id": "", "checked": 0,
+ "total": 0, "gone": [], "unclear": []}
+ return _check_public(state)
+ return _check_public(contract.link_check.start(
+ lambda check_id: _run_link_check(contract, check_id),
+ initial={"checked": 0, "total": 0, "gone": [], "unclear": []},
+ restart=body.get("restart") is True,
+ ))
def w_links_prune(contract: LinkContract, body):
@@ -195,13 +169,12 @@ def w_links_prune(contract: LinkContract, body):
body = body or {}
if body.get("confirm") is not True:
return {"ok": False, "error": "需要 confirm"}
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is None or state["status"] != "complete":
- return {"ok": False, "error": "没有已完成的检查结果"}
- if body.get("check_id") != state["check_id"]:
- return {"ok": False, "error": "检查结果已过期,请重新检查"}
- planned = [dict(item) for item in state["gone"]]
+ state = contract.link_check.snapshot()
+ if state is None or state["status"] != "complete":
+ return {"ok": False, "error": "没有已完成的检查结果"}
+ if body.get("check_id") != state["check_id"]:
+ return {"ok": False, "error": "检查结果已过期,请重新检查"}
+ planned = [dict(item) for item in state["gone"]]
confirmed, recovered = [], []
for item in planned:
@@ -215,9 +188,8 @@ def w_links_prune(contract: LinkContract, body):
for item in confirmed:
removed += connection.execute(
"DELETE FROM entity_link WHERE id=?", (item["id"],)).rowcount
- with contract.link_check_lock:
- state = contract.link_check_state
- if state is not None and state["check_id"] == body.get("check_id"):
+ with contract.link_check.editing(body.get("check_id")) as state:
+ if state is not None:
state["gone"] = []
return {"ok": True, "removed": removed, "recovered": len(recovered),
"entities": len({item["entity"] for item in confirmed})}
diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.py
index c2eb75cd9..1ba80ac22 100644
--- a/src/peach/web_resource_sync.py
+++ b/src/peach/web_resource_sync.py
@@ -11,15 +11,14 @@ from __future__ import annotations
import os
import re
import shutil
-import threading
import time
-import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Callable, Protocol, Sequence
from .catalog_rules import dir_expr, normalise_code_key, photo_set_title
from .config import LOCATION_ROOT_DECLARATIONS
+from .jobs import BackgroundJob
from .media import remap_managed_path
from .platform import is_unmapped, root_online, translate_ledger_path
@@ -37,9 +36,7 @@ class ResourceSyncContract(Protocol):
stream_root: Path
transcode_root: Path
resource_cleanup_enabled: bool
- resource_scan_lock: threading.Lock
- resource_scan_state: dict | None
- resource_scan_thread: threading.Thread | None
+ resource_scan: BackgroundJob
def cache_bust(self) -> None: ...
def read_connection(self): ...
@@ -309,71 +306,46 @@ def _resource_scan_public(state: dict) -> dict:
def _run_resource_scan(contract: ResourceSyncContract, scan_id: str) -> None:
+ """Scan every mounted source. ``BackgroundJob`` turns a failure into a pollable state."""
+ job = contract.resource_scan
+
def progress(source: dict) -> None:
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is not None and state["scan_id"] == scan_id:
+ with job.editing(scan_id) as state:
+ if state is not None:
state["sources"].append(dict(source))
- try:
- scan = _scan_missing_resources(contract, progress)
- caches = _resource_orphan_plan(contract, scan["missing_ids"])
- result = {
- "ok": True, "sources": scan["sources"],
- "missing": len(scan["missing_ids"]),
- "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
- "by_kind": caches["summary"]},
- }
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is not None and state["scan_id"] == scan_id:
- state.update(status="complete", result=result,
- missing_ids=list(scan["missing_ids"]), completed_at=time.time())
- except Exception as error: # Background failures must become a pollable state.
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is not None and state["scan_id"] == scan_id:
- state.update(status="failed", error=f"{type(error).__name__}: {error}",
- completed_at=time.time())
+ scan = _scan_missing_resources(contract, progress)
+ caches = _resource_orphan_plan(contract, scan["missing_ids"])
+ result = {
+ "ok": True, "sources": scan["sources"],
+ "missing": len(scan["missing_ids"]),
+ "cache": {"files": caches["total_files"], "bytes": caches["total_bytes"],
+ "by_kind": caches["summary"]},
+ }
+ job.update(scan_id, status="complete", result=result,
+ missing_ids=list(scan["missing_ids"]), completed_at=time.time())
def _background_resource_scan(contract: ResourceSyncContract, restart: bool = False) -> dict:
- thread = None
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is not None and state["status"] == "running":
- return _resource_scan_public(state)
- if state is not None and not restart:
- return _resource_scan_public(state)
- scan_id = uuid.uuid4().hex
- state = {
- "scan_id": scan_id, "status": "running", "sources": [],
- "started_at": time.time(), "result": None, "missing_ids": [], "error": "",
- }
- contract.resource_scan_state = state
- thread = threading.Thread(
- target=_run_resource_scan, args=(contract, scan_id), daemon=True,
- name="PeachResourceScanJob",
- )
- contract.resource_scan_thread = thread
- response = _resource_scan_public(state)
- thread.start()
- return response
+ return _resource_scan_public(contract.resource_scan.start(
+ lambda scan_id: _run_resource_scan(contract, scan_id),
+ initial={"sources": [], "result": None, "missing_ids": []},
+ restart=restart,
+ ))
def w_resource_sync_scan(contract: ResourceSyncContract, body=None):
body = body or {}
if body.get("background") is True:
if body.get("status_only") is True:
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if state is None:
- return {
- "ok": True, "status": "idle", "scan_id": "", "sources": [],
- "completed_sources": 0,
- "total_sources": len(LOCATION_ROOT_DECLARATIONS),
- }
- return _resource_scan_public(state)
+ state = contract.resource_scan.snapshot()
+ if state is None:
+ return {
+ "ok": True, "status": "idle", "scan_id": "", "sources": [],
+ "completed_sources": 0,
+ "total_sources": len(LOCATION_ROOT_DECLARATIONS),
+ }
+ return _resource_scan_public(state)
return _background_resource_scan(contract, restart=body.get("restart") is True)
scan = _scan_missing_resources(contract)
caches = _resource_orphan_plan(contract, scan["missing_ids"])
@@ -416,13 +388,12 @@ def w_resource_sync_apply(contract: ResourceSyncContract, body):
raise ValueError("resource sync requires confirmation")
scan_id = str(body.get("scan_id") or "")
if scan_id:
- with contract.resource_scan_lock:
- state = contract.resource_scan_state
- if (state is None or state["scan_id"] != scan_id
- or state["status"] != "complete"):
- raise ValueError("resource scan expired; scan again")
- candidates = list(state["missing_ids"])
- sources = [dict(source) for source in state["result"]["sources"]]
+ state = contract.resource_scan.snapshot()
+ if (state is None or state["scan_id"] != scan_id
+ or state["status"] != "complete"):
+ raise ValueError("resource scan expired; scan again")
+ candidates = list(state["missing_ids"])
+ sources = [dict(source) for source in state["result"]["sources"]]
# Do not trust the background result at write time. Recheck only its bounded
# candidate set; online sources and unreadable directories retain the safe skip.
missing_ids = _recheck_resource_scan_ids(contract, candidates)
diff --git a/src/peach/web_review.py b/src/peach/web_review.py
index 1872f0952..dcf6526e2 100644
--- a/src/peach/web_review.py
+++ b/src/peach/web_review.py
@@ -11,10 +11,8 @@ from __future__ import annotations
import hashlib
import json
-import os
import re
import time
-import uuid
from pathlib import Path, PurePosixPath
from typing import Protocol
from urllib.parse import quote
@@ -32,6 +30,7 @@ from .entities import (
resolve_entity,
upsert_asset_entity,
)
+from .fsutil import atomic_write_bytes
from .metadata_policy import SOURCE_SPECS
from .review_csv import read_rows
@@ -892,10 +891,8 @@ def _install_performer_avatar(contract: ReviewContract, entity_id: str) -> int:
kind = (kind_row[0] if kind_row and kind_row[0] in {"performer", "creator"}
else "performer")
destination = contract.avatar_root / f"{kind}-{int(entity_id)}.img"
- # 先写临时文件再原子替换:中途失败不会留下半张图被 `/entity-image` 读到。
- staging = destination.with_name(f"{destination.name}.{uuid.uuid4().hex}.tmp")
- staging.write_bytes(body)
- os.replace(staging, destination)
+ # 原子替换:中途失败不会留下半张图被 `/entity-image` 读到。
+ atomic_write_bytes(destination, body)
Path(f"{destination}.ct").write_text(content_type, encoding="utf-8")
Path(f"{destination}.provenance.json").write_text(json.dumps({
"source": "performer avatar review",
@@ -944,10 +941,8 @@ def _install_studio_logo(contract: ReviewContract, studio: str) -> int:
raise ValueError(f"不支持的图片格式:{source.suffix}")
contract.logo_root.mkdir(parents=True, exist_ok=True)
destination = contract.logo_root / f"{key}.img"
- # 先写临时文件再原子替换:中途失败不会留下半张图被 `/logo` 读到。
- staging = destination.with_name(f"{destination.name}.{uuid.uuid4().hex}.tmp")
- staging.write_bytes(source.read_bytes())
- os.replace(staging, destination)
+ # 原子替换:中途失败不会留下半张图被 `/logo` 读到。
+ atomic_write_bytes(destination, source.read_bytes())
Path(f"{destination}.ct").write_text(content_type, encoding="utf-8")
Path(f"{destination}.provenance.json").write_text(json.dumps({
"source": "studio logo review",
diff --git a/src/peach/windows_update.py b/src/peach/windows_update.py
index f058f4246..e534ddf88 100644
--- a/src/peach/windows_update.py
+++ b/src/peach/windows_update.py
@@ -10,6 +10,8 @@ from datetime import datetime
from pathlib import Path
from typing import Callable
+from .fsutil import atomic_write_text
+
WINDOWS_TRAY_INPUTS = (
"src/peach/",
@@ -76,16 +78,10 @@ class WindowsUpdateInstaller:
self.log_path = self.log_dir / "windows-source-sync.log"
def mark_pending(self, commit: str, changed_paths: tuple[str, ...]) -> None:
- self.pending_path.parent.mkdir(parents=True, exist_ok=True)
- temporary = self.pending_path.with_suffix(".tmp")
- temporary.write_text(
- json.dumps(
- {"commit": commit, "changed_paths": list(changed_paths)},
- ensure_ascii=False, indent=2,
- ),
- encoding="utf-8",
- )
- os.replace(temporary, self.pending_path)
+ atomic_write_text(self.pending_path, json.dumps(
+ {"commit": commit, "changed_paths": list(changed_paths)},
+ ensure_ascii=False, indent=2,
+ ))
def pending(self) -> PendingWindowsUpdate | None:
try:
diff --git a/tests/test_fsutil.py b/tests/test_fsutil.py
new file mode 100644
index 000000000..3e87ab032
--- /dev/null
+++ b/tests/test_fsutil.py
@@ -0,0 +1,73 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+
+from peach.fsutil import atomic_path, atomic_write_bytes, atomic_write_text
+
+
+class AtomicWriteTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+
+ def leftovers(self) -> list[str]:
+ return sorted(path.name for path in self.root.rglob("*.tmp*"))
+
+ def test_a_write_lands_and_leaves_nothing_behind(self):
+ target = self.root / "nested" / "marker.json"
+ returned = atomic_write_text(target, '{"a": 1}')
+ self.assertEqual(returned, target)
+ self.assertEqual(target.read_text(encoding="utf-8"), '{"a": 1}')
+ self.assertEqual(self.leftovers(), [])
+
+ def test_a_failed_write_keeps_the_old_content_and_drops_the_staging_file(self):
+ target = self.root / "marker.json"
+ atomic_write_text(target, "old")
+ with self.assertRaises(RuntimeError):
+ with atomic_path(target) as temporary:
+ temporary.write_text("new", encoding="utf-8")
+ raise RuntimeError("boom")
+ # 关键断言:读的人只能看到上一版,而不是一半的新版。
+ self.assertEqual(target.read_text(encoding="utf-8"), "old")
+ self.assertEqual(self.leftovers(), [])
+
+ def test_the_staging_file_sits_next_to_the_target(self):
+ # 跨卷的 os.replace 不是原子的,所以临时文件必须和目标同目录。
+ target = self.root / "deep" / "marker.json"
+ with atomic_path(target) as temporary:
+ temporary.write_text("x", encoding="utf-8")
+ self.assertEqual(temporary.parent, target.parent)
+
+ def test_the_staging_file_keeps_the_target_extension(self):
+ # FFmpeg 和 PIL 按扩展名决定输出格式,`x.tmp` 会让它们直接失败。
+ seen: list[str] = []
+ with atomic_path(self.root / "5_4.jpg") as temporary:
+ seen.append(temporary.suffix)
+ temporary.write_bytes(b"\xff\xd8")
+ with atomic_path(self.root / "state", suffix=".json") as temporary:
+ seen.append(temporary.suffix)
+ temporary.write_bytes(b"{}")
+ self.assertEqual(seen, [".jpg", ".json"])
+
+ def test_two_writers_to_one_target_do_not_share_a_staging_name(self):
+ target = self.root / "cover.jpg"
+ with atomic_path(target) as first:
+ with atomic_path(target) as second:
+ self.assertNotEqual(first, second)
+ second.write_bytes(b"second")
+ first.write_bytes(b"first")
+ self.assertEqual(target.read_bytes(), b"first")
+ self.assertEqual(self.leftovers(), [])
+
+ def test_bytes_can_be_written_with_a_tightened_mode(self):
+ target = self.root / "review-cache.json"
+ atomic_write_bytes(target, b"payload", mode=0o600)
+ self.assertEqual(target.read_bytes(), b"payload")
+ if os.name != "nt":
+ self.assertEqual(target.stat().st_mode & 0o777, 0o600)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_jobs.py b/tests/test_jobs.py
index 377312518..f6ebae889 100644
--- a/tests/test_jobs.py
+++ b/tests/test_jobs.py
@@ -1,11 +1,14 @@
import os
import signal
import tempfile
+import threading
+import time
import unittest
from pathlib import Path
from unittest.mock import patch
from peach.jobs import (
+ BackgroundJob,
DiskGuard,
DiskSpaceDenied,
JobAlreadyRunning,
@@ -158,3 +161,102 @@ class JobMainTests(unittest.TestCase):
self.assertEqual(job_main(lambda: self._parser(lock), run, []), 7)
self.assertEqual(seen, [True], "run 执行期间锁文件必须还在")
self.assertFalse(lock.exists(), "退出后锁要释放")
+
+
+class BackgroundJobTests(unittest.TestCase):
+ """服务里的后台任务状态机。
+
+ 死链检查和资源对账原先各写一份,共用的不只是形状,还有几条容易漏的约定:
+ 重复点击不许把在跑的那轮丢掉、被顶掉的线程不许再写状态、后台异常必须变成
+ 可轮询的 failed。这些都散在两处的话,下一个照抄的人漏哪条都不会有人发现。
+ """
+
+ def _job(self) -> BackgroundJob:
+ return BackgroundJob("PeachTestJob", id_key="check_id")
+
+ def test_a_fresh_job_has_no_state_at_all(self):
+ """没跑过就是 None,而不是一个假装跑过的空状态。"""
+ self.assertIsNone(self._job().snapshot())
+
+ def test_repeated_clicks_do_not_replace_the_round_that_is_running(self):
+ job = self._job()
+ release = threading.Event()
+ started = threading.Event()
+
+ def work(_job_id: str) -> None:
+ started.set()
+ release.wait(5)
+
+ first = job.start(work)
+ started.wait(5)
+ try:
+ again = job.start(work, restart=True)
+ self.assertEqual(again["check_id"], first["check_id"])
+ self.assertEqual(again["status"], "running")
+ finally:
+ release.set()
+ job.stop()
+
+ def test_restart_is_required_to_replace_a_finished_round(self):
+ job = self._job()
+ job.start(lambda job_id: job.update(job_id, status="complete"))
+ for _ in range(500):
+ if job.snapshot()["status"] == "complete":
+ break
+ time.sleep(0.01)
+ done = job.snapshot()
+ self.assertEqual(done["status"], "complete")
+ # 不带 restart 只是查现状:一份跑完的结果不该被一次误点清掉。
+ self.assertEqual(job.start(lambda _id: None)["check_id"], done["check_id"])
+ self.assertNotEqual(
+ job.start(lambda _id: None, restart=True)["check_id"], done["check_id"])
+
+ def test_a_superseded_worker_can_no_longer_touch_the_state(self):
+ """被顶掉的线程还继续写,前端就会看到新一轮的 id 配旧一轮的进度。"""
+ job = self._job()
+ stale = job.start(lambda _id: None, initial={"checked": 0})["check_id"]
+ job.state = {"check_id": "fresh", "status": "running", "checked": 0}
+ self.assertFalse(job.update(stale, checked=99))
+ with job.editing(stale) as state:
+ self.assertIsNone(state)
+ self.assertEqual(job.snapshot()["checked"], 0)
+
+ def test_a_raising_worker_becomes_a_pollable_failure(self):
+ job = self._job()
+
+ def work(_job_id: str) -> None:
+ raise RuntimeError("上游没了")
+
+ job.start(work)
+ for _ in range(500):
+ if job.snapshot()["status"] != "running":
+ break
+ time.sleep(0.01)
+ state = job.snapshot()
+ self.assertEqual(state["status"], "failed")
+ self.assertEqual(state["error"], "RuntimeError: 上游没了")
+ self.assertIn("completed_at", state)
+
+ def test_the_snapshot_is_deep_enough_to_project_outside_the_lock(self):
+ """公开投影在锁外算,所以快照不能和 worker 共享同一个列表对象。"""
+ job = self._job()
+ job.state = {"check_id": "x", "status": "running", "gone": [{"id": 1}]}
+ snapshot = job.snapshot()
+ snapshot["gone"].append({"id": 2})
+ snapshot["gone"][0]["id"] = 9
+ self.assertEqual(job.state["gone"], [{"id": 1}])
+
+ def test_stop_drops_the_state_and_waits_for_the_worker(self):
+ job = self._job()
+ release = threading.Event()
+ finished = threading.Event()
+
+ def work(_job_id: str) -> None:
+ release.wait(5)
+ finished.set()
+
+ job.start(work)
+ release.set()
+ job.stop(timeout=5)
+ self.assertTrue(finished.is_set())
+ self.assertIsNone(job.snapshot())
diff --git a/tests/test_web_links.py b/tests/test_web_links.py
index bb41d9542..556d333d0 100644
--- a/tests/test_web_links.py
+++ b/tests/test_web_links.py
@@ -2,7 +2,6 @@
import sqlite3
import sys
import tempfile
-import threading
import unittest
from contextlib import contextmanager
from pathlib import Path
@@ -10,6 +9,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from peach import web_links # noqa: E402
+from peach.jobs import BackgroundJob # noqa: E402
SCHEMA = """
CREATE TABLE entity(id INTEGER PRIMARY KEY, kind TEXT, canonical_name TEXT);
@@ -31,9 +31,7 @@ class FakeContract:
def __init__(self, db: Path):
self.db_path = db
- self.link_check_lock = threading.Lock()
- self.link_check_state = None
- self.link_check_thread = None
+ self.link_check = BackgroundJob("PeachLinkCheckJob", id_key="check_id")
@contextmanager
def read_connection(self):
@@ -108,7 +106,7 @@ class SummaryTests(unittest.TestCase):
def test_prune_refuses_a_stale_check_id(self):
"""拿一份放了半天的清单去删,删的可能是早已改好的链接。"""
- self.contract.link_check_state = {
+ self.contract.link_check.state = {
"check_id": "fresh", "status": "complete", "checked": 3, "total": 3,
"gone": [{"id": 1, "entity": "凉森玲梦", "link_kind": "social",
"label": "X @a", "url": "https://x.com/a", "note": "HTTP 404"}],
@@ -126,7 +124,7 @@ class SummaryTests(unittest.TestCase):
第一条重验仍是 404,删;第二条重验回了 200,保留并计入 recovered。
"""
- self.contract.link_check_state = {
+ self.contract.link_check.state = {
"check_id": "fresh", "status": "complete", "checked": 3, "total": 3,
"gone": [
{"id": 1, "entity": "凉森玲梦", "link_kind": "social", "label": "X @a",