Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: 完善运行一致性、关系筛选与 wheel 安装

longmeidao714401db2197
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index a467622b5..dbc2101a9 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -21,6 +21,28 @@ env:
PYTHONIOENCODING: "utf-8"
jobs:
+ wheel-smoke:
+ name: wheel 最小安装 / ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [windows-latest, macos-latest]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.14'
+ - name: 构建并安装正式 wheel
+ shell: bash
+ run: |
+ python -m pip wheel . --no-deps --no-cache-dir -w wheelhouse
+ python -m pip install --no-cache-dir wheelhouse/*.whl
+ python -m pip check
+ - name: 源码树外冒烟
+ shell: bash
+ run: |
+ cd "$RUNNER_TEMP"
+ python "$GITHUB_WORKSPACE/scripts/smoke_wheel.py"
python:
name: ${{ matrix.os }} / Python ${{ matrix.python }}
runs-on: ${{ matrix.os }}
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 000000000..54d658cc4
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,3 @@
+recursive-include migrations *.sql
+recursive-include web *
+recursive-include resources *.png *.ico *.icns
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 5a158a30f..261edf5b7 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -5,6 +5,9 @@
## 界面、媒体与复核的既定判据
+- Windows 和有 TLS 的 macOS 托盘入口由 HTTP 导航进程与 HTTPS 业务进程组成;HTTP 的 `/healthz` 仅证明跳转进程存活,`/healthz?ready=1` 在业务入口验证配置、页面、数据库和迁移校验和。
+- wheel 将 `web`、`migrations`、`resources` 装入 `peach/_resources`;源码维护位置不变。`scripts/smoke_wheel.py` 必须用已安装 wheel 的解释器在仓库外运行,只使用临时账本。
+
页面密度、控件、提示与响应式的实现门槛见 `.claude/skills/peach-web-ui/SKILL.md`,这里只留代码看不出来的判据。
- 截图与视觉验收的画面保护:审查遮挡(设置面板「安全」组,`#censorSetting`,localStorage `peach-censor`)默认关闭、不在导航栏。只有当本轮截图会交给会审查内容的模型(自动视觉审查或外发工具)时才开启,开完记得关;普通个人浏览一律不遮挡。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index c6b7f292d..a29394bed 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -4,12 +4,13 @@
## 已有骨架、尚未完成(6 项)
-本轮实施顺序(评审来源:[外部复评](https://chatgpt.com/c/6a9ad810-6148-83e9-95dd-6b58ef28e7ec),按当前源码核对):
+本轮实施顺序(评审来源:[外部复评](https://chatgpt.com/c/6a9ad810-6148-83e9-95dd-6b58ef28e7ec),按当前源码核对;候选实现与生产验收分开):
- 运行与一致性:HTTP 只跳转 HTTPS;业务与调度由单一应用拥有;成功提交后失效缓存;缓存有界;可更新图片可复验;列表参数有上下界。
- 数据与查询:标签、实体筛选从关系索引驱动;随机排序有唯一次序;重复索引与外键启用先做副本验证;补固定规模基准。
- 安装与诊断:下面第 12、13、21、22、23 项按依赖实施,覆盖最小源码安装、wheel 资源、仓库外启动、就绪检查。独立桌面制品及操作系统 VM 验收仍按第 15、21 项推进。
- 后续结构:显式 API 模型、前端构建与高频页面迁移、候选分页、任务持久化按垂直功能实施;不为 AppContext 或文件尺寸单独做全仓搬迁。
+ 当前已实现运行缓存、关系筛选、wheel 资源、仓库外冒烟和分级健康检查;Windows 基础依赖安装通过。真实库只读对照七轮中位数:标签 195.5→25.5 ms、创作者 148.8→45.6 ms、女优 162.7→15.7 ms、厂牌 162.0→19.6 ms,返回 ID 与总数一致;这不是浏览器端延迟。
- Linux 首版候选为 headless、预挂载媒体与独立 wheel。外部容器用了替身依赖,其结果不构成锁定依赖和 Linux 的正式支持证据,优先级低于 Windows/macOS。
外部评审提到的空口令拒绝启动、secret 文件读取、count=0 已有实现;不重复登记。shuffle_key 改变随机浏览的序列语义,先测关系筛选收益再决定。真实 ledger 迁移、双机复制取消和系统级安装另有明确授权边界。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index e60fd7bda..27875be6c 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -5,6 +5,9 @@
## 复用决策门槛
+- 运行一致性复评:复用 `LedgerDatabase.write_transaction` 的提交边界和标准库 `OrderedDict`;HTTP 导航复用 FastAPI/Starlette,图片复验复用 `StaticFiles.is_not_modified` 与 `FileResponse` 的 ETag。列表使用 SQLite 的 IN/UNION 保留隐藏标签与多标签组合,不引入查询框架。
+- wheel 资源复用 setuptools 84.0.0 的 `build_py.copy_tree`,资源位置遵循[官方包内数据建议](https://setuptools.pypa.io/en/stable/userguide/datafiles.html)。自定义钩子仅复制三个既有资源目录,因为源码、桌面构建和前端产物仍共用其维护位置;Windows 基础依赖全新安装及仓库外 API 冒烟已验证。
+
- 先用真实输入做无写入 POC,再决定“直接依赖、固定来源实现、保留自研”三者之一。
- 采用项要记录固定版本、许可证、首个消费者和 Peach 保留的领域边界;候选依赖不得空转。
- 保留自研要记录被拒绝的候选和不可替代约束,不能只写“特殊需求”。
@@ -124,4 +127,3 @@ Python、npm 与 GitHub Actions 的版本由 `.github/dependabot.yml` 每周检
AVBase 已变为 Cloudflare 验证页,批量流程不再请求也不绕过;DUGA Web API 需代理店应用 ID,未配置前
只复用成功日志的精确 URL。MDC-NG 公共仓库只证明 Amazon 日本渠道存在,后端匹配逻辑未公开,故只留
POC 候选。该流程不新增依赖、不写 ledger,操作步骤见 `peach-jav-cover-workflow`。
-
diff --git a/docs/STATUS.md b/docs/STATUS.md
index aab845aac..d7b8b3a6b 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -7,6 +7,8 @@
## 运行态
+- 复评候选代码包含 HTTP 导航入口、提交后缓存失效、图片复验、关系筛选与 wheel 资源;生产仍以下列已验证运行态为准。Windows 最小 wheel 安装与仓库外冒烟已通过,macOS 同项由 CI 验证,未取得本机 macOS 运行证据。
+
- Windows 是当前 ledger writer,入口 `dist\Peach\Peach.exe`;代码、`peach-data`、worktree 和共享传输点同在一个顶层目录,外置盘只提供 `R:\media`。
- 托盘必须以普通权限启动:提升权限后的令牌看不到 CloudDrive 的 `A:` / `B:`,会把 PikPak 和 115 误报为脱盘。
- Windows HTTP 为 `0.0.0.0:80`,HTTPS 为当前 LAN IPv4 的 443,mDNS 名见 `[server].mdns_name`;线上版本 `0.7.13`、`ledger_sync=writer`。
diff --git a/scripts/smoke_wheel.py b/scripts/smoke_wheel.py
new file mode 100644
index 000000000..69495f1d6
--- /dev/null
+++ b/scripts/smoke_wheel.py
@@ -0,0 +1,42 @@
+"""在仅安装 wheel 的解释器中,从源码树外验证资源、迁移和 HTTP 关键入口。"""
+import json
+import os
+import tempfile
+from pathlib import Path
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix="peach-wheel-") as directory:
+ root = Path(directory).resolve()
+ os.environ["PEACH_DATA_ROOT"] = str(root / "data")
+ from fastapi.testclient import TestClient
+ import peach
+ from peach.api import create_app
+ from peach.config import MIGRATIONS_DIR, PeachSettings
+ from peach.migrations import upgrade
+ assert "site-packages" in Path(peach.__file__).parts, peach.__file__
+ assert "_resources" in MIGRATIONS_DIR.parts, MIGRATIONS_DIR
+ database = root / "ledger.db"
+ assert upgrade(database, MIGRATIONS_DIR)
+ settings = PeachSettings(db_path=database, configured=True, token="wheel-smoke")
+ client = TestClient(create_app(settings))
+ try:
+ assert client.get("/healthz").status_code == 200
+ ready = client.get("/healthz?ready=1")
+ assert ready.status_code == 200, ready.text
+ assert client.get("/api/items").status_code == 401
+ headers = {"X-Token": "wheel-smoke"}
+ assert client.get("/api/items", headers=headers).status_code == 200
+ assert client.get("/", headers=headers).status_code == 200
+ assert settings.page_path.is_file()
+ assert (settings.page_path.parent / "app.js").is_file()
+ assert (settings.page_path.parent / "dist" / "peach-ui.js").is_file()
+ assert any(settings.vendor_path.iterdir())
+ print(json.dumps({"module": peach.__file__, "ready": ready.json(),
+ "checks": ["migrations", "web", "vendor", "island", "auth", "items"]}))
+ finally:
+ client.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 3cef433da..8da807413 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -29,7 +29,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_taste_history.py", "test_web_ui.py", "test_web_js.py",
"test_web_perf.py", "test_web_resource_sync.py",
"test_web_review.py", "test_web_settings.py"),
- "media": ("test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
+ "media": ("test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",
"test_interaction.py", "test_media.py", "test_previews.py",
"test_providers.py", "test_segments.py", "test_streaming.py",
"test_transcodes.py"),
diff --git a/setup.py b/setup.py
new file mode 100644
index 000000000..270089c18
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,17 @@
+"""将运行时资源装入 wheel,源码树仍是资源的唯一维护位置。"""
+from pathlib import Path
+
+from setuptools import setup
+from setuptools.command.build_py import build_py
+
+
+class BuildWithResources(build_py):
+ def run(self):
+ super().run()
+ root = Path(__file__).resolve().parent
+ destination = Path(self.build_lib) / "peach" / "_resources"
+ for name in ("migrations", "web", "resources"):
+ self.copy_tree(str(root / name), str(destination / name))
+
+
+setup(cmdclass={"build_py": BuildWithResources})
diff --git a/src/peach/api.py b/src/peach/api.py
index 786ec81e6..ef2cd351b 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -263,7 +263,12 @@ def create_app(
# 健康检查常被 HEAD 探测(`curl -I`、各种 uptime 工具)。本仓库其他公开端点
# 都显式声明了 GET+HEAD,只有这个漏了,HEAD 会拿到 405。
@app.api_route("/healthz", methods=["GET", "HEAD"])
- def healthz() -> dict[str, Any]:
+ def healthz(ready: bool = False):
+ if ready:
+ from .health import readiness
+ result = readiness(settings)
+ return JSONResponse(result, status_code=200 if result["ready"] else 503,
+ headers={"Cache-Control": "no-store"})
# 不探测共享目录或迁移数据库;健康检查必须无副作用。
ffmpeg = resolver.ffmpeg()
read_only = bool(sync is not None and sync.read_only)
diff --git a/src/peach/cli.py b/src/peach/cli.py
index fda9f939a..ca23505e7 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -55,6 +55,13 @@ def _serve(args: argparse.Namespace) -> int:
import uvicorn
_require_readable_settings()
+ if args.redirect_origin:
+ from .redirect import create_redirect_app
+ if args.ssl_certfile or args.ssl_keyfile:
+ raise SystemExit("redirect listener must use HTTP")
+ uvicorn.run(create_redirect_app(args.redirect_origin), host=args.host,
+ port=args.port, workers=1)
+ return 0
if bool(args.ssl_certfile) != bool(args.ssl_keyfile):
raise SystemExit("--ssl-certfile and --ssl-keyfile must be provided together")
for path in (args.ssl_certfile, args.ssl_keyfile):
@@ -559,6 +566,7 @@ def build_parser() -> argparse.ArgumentParser:
serve = commands.add_parser("serve", help="run the FastAPI application")
serve.add_argument("--host", default=SERVE_HOST)
+ serve.add_argument("--redirect-origin", default="", help="HTTP navigation to one HTTPS origin")
serve.add_argument("--port", type=int, default=SERVE_PORT)
serve.add_argument("--db", type=Path, default=DEFAULT_DB)
serve.add_argument("--token", default="")
diff --git a/src/peach/health.py b/src/peach/health.py
new file mode 100644
index 000000000..ac63d2085
--- /dev/null
+++ b/src/peach/health.py
@@ -0,0 +1,24 @@
+"""只读就绪检查;不创建账本,不修复或迁移数据。"""
+import sqlite3
+from contextlib import closing
+
+from .config import MIGRATIONS_DIR, PeachSettings
+from .migrations import applied, discover
+
+
+def readiness(settings: PeachSettings) -> dict:
+ checks = {"configured": bool(settings.configured),
+ "web": settings.page_path.is_file(), "database": False, "schema": False}
+ try:
+ with closing(sqlite3.connect(settings.db_path.resolve().as_uri() + "?mode=ro",
+ uri=True, timeout=1)) as connection:
+ connection.execute("PRAGMA query_only=ON")
+ connection.execute("SELECT id FROM asset LIMIT 1").fetchone()
+ checks["database"] = True
+ installed = applied(connection)
+ expected = discover(MIGRATIONS_DIR)
+ checks["schema"] = bool(expected) and all(
+ installed.get(m.version) == m.checksum for m in expected)
+ except (sqlite3.Error, OSError, ValueError):
+ pass
+ return {"ready": all(checks.values()), "checks": checks}
diff --git a/src/peach/redirect.py b/src/peach/redirect.py
new file mode 100644
index 000000000..6e53f7e06
--- /dev/null
+++ b/src/peach/redirect.py
@@ -0,0 +1,36 @@
+"""HTTP 入口只负责探活和导航到固定 HTTPS origin。"""
+from urllib.parse import quote, urlencode, urlsplit
+
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse, RedirectResponse
+
+
+def create_redirect_app(origin: str) -> FastAPI:
+ target = urlsplit(origin)
+ if (target.scheme != "https" or not target.hostname or target.username
+ or target.password or target.path not in ("", "/")
+ or target.query or target.fragment):
+ raise ValueError("redirect origin must be an HTTPS origin")
+ origin = origin.rstrip("/")
+ app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
+
+ @app.api_route("/healthz", methods=["GET", "HEAD"])
+ def healthz():
+ return {"ok": True, "service": "peach-redirect", "scheme": "http"}
+
+ @app.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
+ def redirect(request: Request, path: str):
+ # 写请求不能因 307/308 在另一个 origin 自动重发口令或正文。
+ if request.method not in {"GET", "HEAD"}:
+ return JSONResponse({"error": "HTTPS required"}, status_code=426,
+ headers={"Cache-Control": "no-store"})
+ # 固定 origin,不使用来访 Host;不转发查询串中的口令。
+ query = request.query_params.multi_items()
+ query = urlencode([(key, value) for key, value in query if key != "t"])
+ location = origin + "/" + quote(path, safe="/@:")
+ if query:
+ location += "?" + query
+ return RedirectResponse(location, status_code=302,
+ headers={"Cache-Control": "no-store"})
+
+ return app
diff --git a/src/peach/repository.py b/src/peach/repository.py
index 427374dd0..d95f666b1 100644
--- a/src/peach/repository.py
+++ b/src/peach/repository.py
@@ -16,6 +16,7 @@ class LedgerDatabase:
def __init__(self, db_path: Path):
self.db_path = Path(db_path)
self.write_lock = threading.Lock()
+ self.after_commit = lambda: None
def connect(self, *, write: bool = False) -> sqlite3.Connection:
target = (
@@ -56,6 +57,7 @@ class LedgerDatabase:
raise
else:
connection.commit()
+ self.after_commit()
finally:
connection.close()
diff --git a/src/peach/routes_media.py b/src/peach/routes_media.py
index b74cd1be8..58eb38059 100644
--- a/src/peach/routes_media.py
+++ b/src/peach/routes_media.py
@@ -24,6 +24,7 @@ from fastapi.responses import (
FileResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response,
StreamingResponse,
)
+from starlette.staticfiles import StaticFiles
from . import link_marks, site_icons
from .config import GENERATED_DIR
@@ -64,6 +65,18 @@ _UNSAFE_FILENAME = re.compile('[\\/:*?"<>|]+|[\x00-\x1f]+')
LOGGER = logging.getLogger(__name__)
+def _image_response(request: Request, path: Path, media_type: str | None = None):
+ """固定图片 URL 使用私有缓存,并按文件 ETag 复验。"""
+ response = FileResponse(path, media_type=media_type, stat_result=path.stat())
+ response.headers["Cache-Control"] = "private, no-cache"
+ if StaticFiles().is_not_modified(response.headers, request.headers):
+ return Response(status_code=304, headers={
+ "ETag": response.headers["etag"],
+ "Cache-Control": response.headers["cache-control"],
+ })
+ return response
+
+
def _attachment_disposition(title: str, url: str) -> str:
"""按条目标题构造下载文件名,扩展名沿用上游地址的后缀。
@@ -235,18 +248,14 @@ async def stream_cancel(request: Request, session: str, args: dict[str, str] = D
@router.api_route("/thumb", methods=["GET", "HEAD"])
def thumbnail(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
path = request.app.state.media_engine.file_for(id, thumbnail=True)
- response = FileResponse(path)
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path)
@router.api_route("/photo", methods=["GET", "HEAD"])
def photo(request: Request, id: int, args: dict[str, str] = Depends(require_auth)):
"""图片资产原图。灯箱看大图用这条,瀑布流一律走 `/photo-thumb`。"""
path = request.app.state.media_engine.file_for(id)
- response = FileResponse(path)
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path)
@router.api_route("/photo-thumb", methods=["GET", "HEAD"])
@@ -257,9 +266,7 @@ def photo_thumb(request: Request, id: int, args: dict[str, str] = Depends(requir
path = state.photo_service.thumbnail(id, source)
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
- response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type="image/jpeg")
@router.api_route("/poster", methods=["GET", "HEAD"])
@@ -268,9 +275,7 @@ def poster(request: Request, id: int, c: int = 4, args: dict[str, str] = Depends
path = request.app.state.preview_service.poster(id, c)
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
- response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type="image/jpeg")
@router.api_route("/cover", methods=["GET", "HEAD"])
@@ -279,9 +284,7 @@ def cover(request: Request, code: str = "", args: dict[str, str] = Depends(requi
path = request.app.state.web_contract.cover_path(code)
if path is None:
return JSONResponse({"error": "no cover"}, status_code=404)
- response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type="image/jpeg")
@router.api_route("/endcard-frame", methods=["GET", "HEAD"])
@@ -306,9 +309,7 @@ def avatar(request: Request, id: int, args: dict[str, str] = Depends(require_aut
path = request.app.state.preview_service.avatar(id)
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
- response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = f"public, max-age={AVATAR_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type="image/jpeg")
@router.api_route("/follow-avatar", methods=["GET", "HEAD"])
@@ -430,9 +431,7 @@ def follow_cover(request: Request, id: int, args: dict[str, str] = Depends(requi
return Response(PLACEHOLDER_IMAGE, status_code=404,
media_type=PLACEHOLDER_CONTENT_TYPE,
headers={"cache-control": "no-store"})
- response = FileResponse(path, media_type="image/jpeg")
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type="image/jpeg")
@router.api_route("/logo", methods=["GET", "HEAD"])
@@ -500,6 +499,4 @@ def entity_image(request: Request, kind: str, id: int, args: dict[str, str] = De
path, content_type = request.app.state.preview_service.entity_image(kind, id)
except PreviewUnavailable:
return JSONResponse({"error": "unavailable"}, status_code=404)
- response = FileResponse(path, media_type=content_type)
- response.headers["Cache-Control"] = f"public, max-age={MEDIA_CACHE_SECONDS}"
- return response
+ return _image_response(request, path, media_type=content_type)
diff --git a/src/peach/settings_file.py b/src/peach/settings_file.py
index 6685c3aa4..0a8009f09 100644
--- a/src/peach/settings_file.py
+++ b/src/peach/settings_file.py
@@ -65,7 +65,10 @@ class SettingsFileError(RuntimeError):
def _project_root(module_file: str = __file__, bundle_root: str | None = None) -> Path:
- """源码树保留 `src/` 层;PyInstaller 的资源直接落在 `_MEIPASS`。"""
+ """资源来自源码树、wheel 内的资源目录或 PyInstaller 的 `_MEIPASS`。"""
+ packaged = Path(module_file).resolve().parent / "_resources"
+ if bundle_root is None and packaged.is_dir():
+ return packaged
return (Path(bundle_root) if bundle_root is not None
else Path(module_file).resolve().parents[2])
diff --git a/src/peach/tray.py b/src/peach/tray.py
index 5008182b0..13c8c37c2 100644
--- a/src/peach/tray.py
+++ b/src/peach/tray.py
@@ -455,8 +455,8 @@ def build_macos_service_specs() -> tuple[ServiceSpec, ...]:
"http",
f"http://127.0.0.1:{MACOS_PORT}/healthz",
(
- peach, "serve", "--host", "0.0.0.0", "--port", str(MACOS_PORT),
- "--no-ledger-sync",
+ peach, "serve", "--host", "127.0.0.1", "--port", str(MACOS_PORT),
+ "--no-ledger-sync", "--no-mdns",
),
True,
),
@@ -465,6 +465,11 @@ def build_macos_service_specs() -> tuple[ServiceSpec, ...]:
ca, cert, key = (cert_dir / n for n in
("peach-local-ca.crt", "peach.crt", "peach.key"))
if all(path.is_file() for path in (ca, cert, key)):
+ specs[0] = ServiceSpec(
+ "http", f"http://127.0.0.1:{MACOS_PORT}/healthz",
+ (peach, "serve", "--host", "0.0.0.0", "--port", str(MACOS_PORT),
+ "--redirect-origin", f"https://{MDNS_HOSTNAME}"), True,
+ )
specs.append(ServiceSpec(
"https",
# 健康检查走回环,不走局域网地址。走 `peach.local` 会先解析到本机的
@@ -474,7 +479,7 @@ def build_macos_service_specs() -> tuple[ServiceSpec, ...]:
f"https://127.0.0.1:{MACOS_TLS_PORT}/healthz",
(
peach, "serve", "--host", "0.0.0.0", "--port", str(MACOS_TLS_PORT),
- "--no-mdns", "--no-ledger-sync",
+ "--no-ledger-sync",
"--ssl-certfile", str(cert), "--ssl-keyfile", str(key),
),
str(ca),
@@ -504,7 +509,7 @@ def build_service_specs(
"http://127.0.0.1/healthz",
(
peach, "serve", "--host", "0.0.0.0", "--port", "80",
- "--mdns-address", address, "--no-ledger-sync",
+ "--redirect-origin", f"https://{MDNS_HOSTNAME}",
),
True,
),
@@ -512,7 +517,7 @@ def build_service_specs(
"https",
f"https://{address}/healthz",
(
- peach, "serve", "--host", address, "--port", "443", "--no-mdns",
+ peach, "serve", "--host", address, "--port", "443", "--mdns-address", address,
"--no-ledger-sync",
"--ssl-certfile", str(cert), "--ssl-keyfile", str(key),
),
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.py
index 72a71f8c9..a6130ac3a 100644
--- a/src/peach/web_catalog.py
+++ b/src/peach/web_catalog.py
@@ -128,23 +128,23 @@ def q_items(contract: WebContract, args):
where.append("a.location IN (%s)" % ",".join("?" * len(locs))); par += locs
if args.get("creator"):
where.append(
- "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "WHERE ae.asset_id=a.id AND e.kind='creator' AND e.canonical_name=?)"
+ "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE e.kind='creator' AND e.canonical_name=?)"
); par.append(args["creator"])
if args.get("performer"):
where.append(
- "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "WHERE ae.asset_id=a.id AND e.kind='performer' AND e.canonical_name=?)"
+ "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE e.kind='performer' AND e.canonical_name=?)"
); par.append(args["performer"])
if args.get("studio"):
where.append(
- "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "WHERE ae.asset_id=a.id AND e.kind='studio' AND e.canonical_name=?)"
+ "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE e.kind='studio' AND e.canonical_name=?)"
); par.append(args["studio"])
if args.get("series"):
where.append(
- "EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "WHERE ae.asset_id=a.id AND e.kind='series' AND e.canonical_name=?)"
+ "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE e.kind='series' AND e.canonical_name=?)"
); par.append(args["series"])
# 事务所隔一层:作品是它的成员拍的,`asset_entity` 里没有事务所的行。
if args.get("agency"):
@@ -152,9 +152,9 @@ def q_items(contract: WebContract, args):
if args.get("tag"):
tags = [x for x in args["tag"].split(",") if x]
tag_clause = (
- "((EXISTS(SELECT 1 FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
- "WHERE ae.asset_id=a.id AND e.kind='tag' AND e.canonical_name=?) OR "
- "EXISTS(SELECT 1 FROM asset_tag t WHERE t.asset_id=a.id AND t.tag=?)) AND "
+ "(a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE e.kind='tag' AND e.canonical_name=? UNION "
+ "SELECT t.asset_id FROM asset_tag t WHERE t.tag=?) AND "
+ tag_not_hidden("a.id", "?") + ")"
)
if args.get("tag_match") == "any" and len(tags) > 1:
@@ -228,16 +228,16 @@ def q_items(contract: WebContract, args):
if order is None:
if args.get("sort") == "seed":
sd = int(args.get("seed") or 1) % 99991 or 7
- order = f"((a.id * {sd}) % 99991)"
+ order = f"((a.id * {sd}) % 99991), a.id"
elif args.get("sort") == "daily" or not args.get("sort"):
# 每日轮换:用当天日期做种子打散,同一天顺序固定,隔天自动换一批。
# 不用 RANDOM() —— 那样每次刷新都不同,翻页还会重复/漏掉。
seed = int(time.strftime("%Y%m%d")) % 9973 or 7
- order = f"((a.id * {seed}) % 99991)"
+ order = f"((a.id * {seed}) % 99991), a.id"
else:
order = "a.id DESC"
- lim = min(int(args.get("limit", 60)), 200)
- off = int(args.get("offset", 0))
+ lim = max(1, min(int(args.get("limit", 60)), 200))
+ off = max(0, int(args.get("offset", 0)))
include_total = args.get("count", "1") != "0"
fetch_limit = lim if include_total else lim + 1
sql = ("SELECT a.id,a.location,a.path,a.name,a.catalog_title,a.original_title,a.medium,"
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index e4857ffb0..81fc3c0bb 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -123,7 +123,7 @@ class WebContract:
self.db_path = self.database.db_path
self.snapshot_root = Path(snapshot_root) if snapshot_root is not None else None
self.legacy_snapshot_roots = tuple(Path(path) for path in legacy_snapshot_roots)
- self.cache: dict[str, tuple[float, object]] = {}
+ self.cache: OrderedDict[str, tuple[float, object]] = OrderedDict()
self.cache_lock = threading.Lock()
#: 按资产取键的读缓存,LRU 限界。键空间不封闭的场景走这里,见 `cached_lru()`。
self.keyed_cache: OrderedDict[str, tuple[float, object]] = OrderedDict()
@@ -136,6 +136,7 @@ class WebContract:
self.resource_scan = BackgroundJob("PeachResourceScanJob", id_key="scan_id")
self.link_check = BackgroundJob("PeachLinkCheckJob", id_key="check_id")
self._fts_available: bool | None = None
+ self.database.after_commit = self.cache_bust
def cached(self, key, fn):
"""带 TTL 的读缓存。`fn` 刻意在锁外算——它会读 CSV、查库,拿着锁算会把
@@ -148,10 +149,11 @@ class WebContract:
用代次挡住:写回前确认这期间没有失效过,否则丢弃这次结果。
"""
- now = time.time()
+ now = time.monotonic()
with self.cache_lock:
hit = self.cache.get(key)
if hit and now - hit[0] < CACHE_TTL:
+ self.cache.move_to_end(key)
return hit[1]
generation = self.cache_generation
value = fn()
@@ -160,17 +162,18 @@ class WebContract:
# 时间戳沿用进入时的 now:算得比 TTL 还久的结果直接算过期,
# 宁可下次重算,也不要把一份已经旧了的数据当新的用。
self.cache[key] = (now, value)
+ self.cache.move_to_end(key)
+ while len(self.cache) > 192:
+ self.cache.popitem(last=False)
return value
def cached_lru(self, key, fn, *, maxsize: int = 192, ttl: float = CACHE_TTL):
"""带 TTL 的 LRU 读缓存,给键空间不封闭的场景用(`/api/related` 按资产取键)。
- `cached()` 的字典只在 `cache_bust()` 时清空,所以它的键空间必须封闭——
- stats、tops 只有几个固定键,放得下;related 的键跟着浏览过的资料页数量走,
- 不限界就是无上限的内存增长。LRU 驱逐之外,TTL 与代次失效的语义和
- `cached()` 逐字一致,包括「`fn` 在锁外算」和「失效过就丢弃这次结果」。
+ 与聚合缓存分开计量,容量和 TTL 可由调用方指定。计算在锁外进行,
+ 计算期间发生提交或显式失效时,结果不进入缓存。
"""
- now = time.time()
+ now = time.monotonic()
with self.cache_lock:
hit = self.keyed_cache.get(key)
if hit and now - hit[0] < ttl:
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 57b5987e1..5d3e4a4d0 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -1101,7 +1101,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"clear-jpeg")
self.assertEqual(response.headers["cache-control"],
- f"public, max-age={api_module.MEDIA_CACHE_SECONDS}")
+ "private, no-cache")
cover.fail = True
fallback = await self.client.get(
"/follow-cover?id=7&t=secret", follow_redirects=False)
@@ -1241,7 +1241,16 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(logo.headers["content-type"], "image/png")
self.assertEqual(logo.headers["cache-control"], "public, no-cache")
self.assertEqual(poster.headers["cache-control"],
- f"public, max-age={api_module.MEDIA_CACHE_SECONDS}")
+ "private, no-cache")
+ fresh = await self.client.get("/poster?id=1&c=4", headers={
+ **headers, "If-None-Match": poster.headers["etag"],
+ })
+ self.assertEqual(fresh.status_code, 304)
+ self.assertEqual(fresh.content, b"")
+ denied = await self.client.get("/poster?id=1&c=4", headers={
+ "If-None-Match": poster.headers["etag"],
+ })
+ self.assertEqual(denied.status_code, 401)
async def test_endcard_frame_is_authenticated_and_confined_to_evidence_root(self):
denied = await self.client.get(
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 31677ae07..8091b921d 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1463,6 +1463,17 @@ class WebDataTests(unittest.TestCase):
self.assertEqual([item["id"] for item in newest["items"]], [1, 2])
self.assertEqual([item["id"] for item in biggest["items"]], [2, 1])
+ def test_items_pagination_is_bounded_and_seed_collisions_have_a_unique_order(self):
+ with self.contract.write_transaction() as connection:
+ connection.execute(
+ "INSERT INTO asset(id,location,path,name,medium) VALUES(99992,'local','collision.mp4','collision.mp4','video')")
+ args = {"seed": "1", "limit": "1"}
+ first = rm_web.q_items(self.contract, args)
+ second = rm_web.q_items(self.contract, {**args, "offset": "1"})
+ self.assertEqual([first["items"][0]["id"], second["items"][0]["id"]], [1, 99992])
+ bounded = rm_web.q_items(self.contract, {"limit": "-1", "offset": "-2", "seed": "1"})
+ self.assertEqual([item["id"] for item in bounded["items"]], [1])
+
def test_sort_takes_a_direction_and_puts_missing_values_last_either_way(self):
"""方向是独立参数,升序也把空值排在最后。
diff --git a/tests/test_runtime_consistency.py b/tests/test_runtime_consistency.py
new file mode 100644
index 000000000..1c2ac43c8
--- /dev/null
+++ b/tests/test_runtime_consistency.py
@@ -0,0 +1,101 @@
+"""事务、图片复验和 HTTP 入口的行为验证。"""
+import sqlite3
+import tempfile
+import unittest
+from pathlib import Path
+
+from fastapi import FastAPI, Request
+from fastapi.testclient import TestClient
+
+from peach.redirect import create_redirect_app
+from peach.routes_media import _image_response
+from peach.web_state import WebContract
+from peach.config import PeachSettings
+from peach.health import readiness
+from support.ledger import fresh_ledger
+
+
+class RuntimeConsistencyTests(unittest.TestCase):
+ def test_readiness_distinguishes_missing_database_and_pending_schema(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ path = root / "ledger.db"
+ settings = PeachSettings(db_path=path, configured=True)
+ self.assertFalse(readiness(settings)["ready"])
+ self.assertFalse(path.exists())
+ fresh_ledger(root)
+ self.assertTrue(readiness(settings)["ready"])
+ connection = sqlite3.connect(path)
+ try:
+ connection.execute("DELETE FROM schema_migration WHERE version=(SELECT max(version) FROM schema_migration)")
+ connection.commit()
+ finally:
+ connection.close()
+ result = readiness(settings)
+ self.assertTrue(result["checks"]["database"])
+ self.assertFalse(result["checks"]["schema"])
+
+ def test_commit_invalidates_values_read_during_transaction(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory).resolve() / "test.db"
+ with sqlite3.connect(path) as connection:
+ connection.execute("CREATE TABLE sample(value INTEGER)")
+ connection.execute("INSERT INTO sample VALUES(0)")
+ connection.close()
+ contract = WebContract(path)
+
+ def read():
+ with contract.read_connection() as connection:
+ return connection.execute("SELECT value FROM sample").fetchone()[0]
+
+ with contract.write_transaction() as connection:
+ contract.cache_bust()
+ connection.execute("UPDATE sample SET value=1")
+ self.assertEqual(contract.cached("sample", read), 0)
+ self.assertEqual(contract.cached("sample", read), 1)
+ generation = contract.cache_generation
+ with self.assertRaises(ValueError):
+ with contract.write_transaction() as connection:
+ connection.execute("UPDATE sample SET value=2")
+ raise ValueError("rollback")
+ self.assertEqual(contract.cache_generation, generation)
+ self.assertEqual(read(), 1)
+
+ def test_aggregate_cache_is_bounded_and_keeps_recent_hits(self):
+ contract = WebContract(Path("unused.db"))
+ for key in range(192):
+ contract.cached(str(key), lambda: key)
+ contract.cached("0", lambda: -1)
+ contract.cached("new", lambda: 999)
+ self.assertEqual(len(contract.cache), 192)
+ self.assertIn("0", contract.cache)
+ self.assertNotIn("1", contract.cache)
+
+ def test_http_navigation_uses_fixed_origin_and_does_not_replay_writes(self):
+ with TestClient(create_redirect_app("https://peach.test")) as client:
+ health = client.get("/healthz")
+ self.assertEqual(health.json()["service"], "peach-redirect")
+ response = client.get("/items?q=a&q=b&t=secret", headers={"Host": "evil.test"},
+ follow_redirects=False)
+ self.assertEqual(response.headers["location"], "https://peach.test/items?q=a&q=b")
+ self.assertEqual(client.post("/api/action", json={"value": 1}).status_code, 426)
+
+ def test_mutable_image_revalidates_after_replacement(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory).resolve() / "cover.jpg"
+ path.write_bytes(b"first")
+ app = FastAPI()
+
+ @app.get("/image")
+ def image(request: Request):
+ return _image_response(request, path)
+
+ with TestClient(app) as client:
+ response = client.get("/image")
+ headers = {"If-None-Match": response.headers["etag"]}
+ self.assertEqual(client.get("/image", headers=headers).status_code, 304)
+ path.write_bytes(b"replacement")
+ updated = client.get("/image", headers=headers)
+ self.assertEqual(updated.status_code, 200)
+ self.assertEqual(updated.content, b"replacement")
+ self.assertEqual(updated.headers["cache-control"], "private, no-cache")
diff --git a/tests/test_tray.py b/tests/test_tray.py
index acaa3437b..86c61fdff 100644
--- a/tests/test_tray.py
+++ b/tests/test_tray.py
@@ -67,10 +67,15 @@ class TrayTests(unittest.TestCase):
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(lan_address="192.0.2.10", tls_dir=tls_dir)
- owners = [spec for spec in specs if "--no-ledger-sync" not in spec.command]
+ owners = [spec for spec in specs if "--no-ledger-sync" not in spec.command
+ and "--redirect-origin" not in spec.command]
self.assertEqual(owners, [])
for spec in specs:
- self.assertIn("--no-ledger-sync", spec.command)
+ if spec.name == "https":
+ self.assertIn("--no-ledger-sync", spec.command)
+ self.assertNotIn("--no-mdns", spec.command)
+ else:
+ self.assertIn("--redirect-origin", spec.command)
@unittest.skipUnless(
os.name == "nt", "macOS 走 build_macos_service_specs,不发布 LAN 地址"
@@ -621,7 +626,7 @@ class MacMenuBarTests(unittest.TestCase):
command = specs["https"].command
self.assertIn("--ssl-certfile", command)
# 两份服务只能有一份发布 mDNS,否则同名记录互相打架。
- self.assertIn("--no-mdns", command)
+ self.assertNotIn("--no-mdns", command)
self.assertTrue(str(specs["https"].verify).endswith("peach-local-ca.crt"))