Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix: restore verified peach.local publication

Peach local maintenancedce3ceb3529d
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 5b033de57..8509be897 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -21,7 +21,7 @@ This is durable operating knowledge, not a per-session transcript.
## Operations
- Main command: `peach serve|migrate` after editable installation.
-- `peach serve` 默认发布 DNS-SD;使用 `--no-mdns` 可关闭。Windows 走系统 `DnsServiceRegister`,`Peach` 是服务实例,health 的 `mdns` 是实际可访问主机(当前 `LMD-DST.local`),不是品牌别名;其他平台走 zeroconf。注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。不要再把 Windows 的服务注册成功写成 `peach.local` A 记录成功。
+- `peach serve` 默认用 Python zeroconf 发布唯一入口 `peach.local`;使用 `--no-mdns` 可关闭。必须保留迁移前已验证的 `Zeroconf()` 全合格网卡语义,不要缩窄为单一 IPv4,也不要改用只能发布服务/SRV 的 Windows `DnsServiceRegister`。注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。mDNS 修改的验收门槛是:单元测试、运行态 health、DNS-SD 查询、主机名解析,以及一台真实 LAN 客户端;监听端口枚举或注册回调不能单独证明可用。
- TLS 仅在同时提供 `--ssl-certfile` 和 `--ssl-keyfile` 时启用;`.local` 使用本地 CA,不使用 Let's Encrypt,证书和私钥留在 `R:\peach-data\secrets`。
- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.
- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 6e9dacc7d..e34113378 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -4,8 +4,8 @@ Last verified: 2026-08-14
## Runtime
-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 27900; health mode is `fastapi`.
-- Windows mDNS now correctly publishes `Peach` as the DNS-SD service and `LMD-DST.local` as its actual SRV host on interface 9/address `192.168.50.162`. The earlier `peach.local` claim was invalid because `DnsServiceRegister` does not create arbitrary host aliases. A second LAN device still needs to confirm `http://LMD-DST.local/`; no firewall or router rule was changed.
+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, server PID observed as 58124; health mode is `fastapi`.
+- `peach.local` is again the single official LAN entry. The publisher restores the verified pre-migration behavior: Python zeroconf listens on all eligible interfaces and publishes `peach.local -> 192.168.50.162`. Production health reports `mdns_backend=zeroconf-all-interfaces`; same-host DNS-SD discovery and `getaddrinfo('peach.local')` both resolved the correct address after restart. A second LAN device remains the final external check; no firewall or router rule was changed.
- Stash: `127.0.0.1:9999`, PID observed as 35332.
- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.
- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.
@@ -31,7 +31,7 @@ Runtime PIDs are observations, not configuration; always re-check them.
- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.
- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.
- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.
-- 46 isolated tests, Python static compilation and JavaScript parse validation passed under Python 3.14/Node.
+- 47 isolated tests, Python static compilation and JavaScript parse validation passed under Python 3.14/Node.
- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.
- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.
- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.
@@ -44,6 +44,7 @@ Runtime PIDs are observations, not configuration; always re-check them.
- `scripts/import_stash_entities.py` reconciled the Stash public performer contract into Peach without making Stash authoritative: 383 exact stable refs, 52 aliases/search terms and two explicitly declared X links were imported. Of 42 non-placeholder Stash images, 14 passed the 512 px short-side gate and were cached with provenance; 28 smaller images were rejected. Top entries including 一个ren、高桥千凛 and 小桃 now use 720 px-class cached portraits.
- Static/unit/API production checks passed after restart: home/entity routes, FC2/Prestige logos, canonical aliases and a local-media 1 KiB `206 Partial Content` response. No browser instance was connected, so desktop and 390×844 visual verification remain pending.
- The 20:36 Peach restart was launched only after verifying the port-80 command line in the host session. The replacement process can see CloudDrive: asset 4289 again passed `video/mp4` 1 KiB `206 Partial Content` and poster `200`; local asset 1 passed the same Range contract. A sandbox drive check is not authoritative.
+- The mDNS regression fix was deployed after verifying the old port-80 command line. The replacement PID 58124 passed health, local DNS-SD discovery, Windows hostname resolution and CloudDrive asset 4289 with a 1 KiB `206 Partial Content` response. The active creator-board sampler and its FFmpeg children were not touched.
- The original Peach process could not see CloudDrive `A:`/`B:` even though CloudDrive was running. After confirming zero copy tasks and no I/O, CloudDrive and Peach were restarted in the same execution context. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks. Drive-letter visibility differs by Windows token, so the HTTP stream check is the authoritative service test.
## Batch jobs
diff --git a/docs/adr/0004-network-and-profile-boundary.md b/docs/adr/0004-network-and-profile-boundary.md
index cbe20e395..a86e4659f 100644
--- a/docs/adr/0004-network-and-profile-boundary.md
+++ b/docs/adr/0004-network-and-profile-boundary.md
@@ -9,7 +9,7 @@
- online 资产、追更和外部数据源是正式能力,不再受“绝不出网”旧约束;每个 connector 必须显式授权、控频、标注来源与保留策略。
- schema 预留 `app_user`/`profile`,当前只创建本地默认身份,不开放注册、密码找回、公共会话或复杂 RBAC。
- 远程访问以后可选择 VPN/Tunnel,或 DDNS + 反向代理 + HTTPS;应用本身不直接裸露公网端口。
-- 局域网服务由 FastAPI 生命周期发布 DNS-SD;可用 `--no-mdns` 关闭,不再依赖旧 HTTP server。Windows 使用系统 `DnsServiceRegister`,以 `Peach` 为服务实例、实际计算机名(当前 `LMD-DST.local`)为 SRV 主机,并绑定首选 LAN 接口;该 API 不创建任意 `peach.local` A 记录。若必须使用品牌化主机别名,应由路由器本地 DNS/反代 DNS 或经验证的专用 responder 提供。其他平台保留 zeroconf,可直接发布自定义 `.local` 主机名。
+- 局域网服务由 FastAPI 生命周期发布唯一入口 `peach.local`;可用 `--no-mdns` 关闭,不再依赖旧 HTTP server。所有平台统一使用 Python zeroconf,并在 Windows 保留迁移前已实际成功的全合格网卡监听语义。不得只凭 UDP 5353 监听者数量推断冲突,也不得用 DNS-SD 注册回调替代客户端解析验证。详细复盘见 ADR-0009。
- Uvicorn 支持显式证书/私钥的本机 TLS。`.local` 不能申请公开受信的 Let's Encrypt 证书;局域网需要 TLS 时使用受各客户端信任的本地 CA(如 mkcert),证书材料只放 `R:\peach-data\secrets`。
- 公网启用前必须完成强口令/身份、TLS、反代可信头、CSRF/速率限制、secret storage、审计与备份恢复验收。
diff --git a/docs/adr/0009-restore-verified-mdns-publication.md b/docs/adr/0009-restore-verified-mdns-publication.md
new file mode 100644
index 000000000..2bf040132
--- /dev/null
+++ b/docs/adr/0009-restore-verified-mdns-publication.md
@@ -0,0 +1,37 @@
+# ADR-0009:恢复已验证的 peach.local 发布语义
+
+- 状态:Accepted
+- 日期:2026-08-14
+- 取代:ADR-0004 中 Windows 使用 `DnsServiceRegister` 的局部决策
+
+## 背景
+
+迁移前的 `rm-web.py` 使用无参数 `Zeroconf()`,在全部合格网卡发布
+`peach._http._tcp.local`,其主机为 `peach.local`。真实 LAN 客户端曾成功访问。
+
+FastAPI 迁移先把发布器改成 `Zeroconf(interfaces=[address])`,但没有针对这一网络语义
+变化做客户端回归。一次客户端解析失败后,又因 Steam、CrossPaste 等进程同时监听 UDP
+5353,直接将共享端口认定为根因,改用 Windows `DnsServiceRegister`。该实现的注册回调和
+health 均成功,但它只能可靠发布服务及真实计算机 SRV 主机,不能提供产品需要的
+`peach.local` 主机记录。
+
+## 决策
+
+- 恢复迁移前的 `Zeroconf()` 全合格网卡监听与 `allow_name_change=True` 发布语义。
+- Windows、macOS 和 Linux 使用同一发布器;删除 Windows ctypes DNS-SD 分支和重复的别名响应器。
+- `peach.local` 是唯一正式 LAN 入口;计算机名只作为诊断信息,不进入产品导航。
+- 修改 mDNS 时必须对照已成功基线,一次只改变一个网络变量。
+- 验收必须包含单元测试、运行态 health、DNS-SD 服务发现、主机名解析和另一台 LAN 客户端。
+ 端口枚举、成功回调、同机 health 都只能作为局部证据。
+
+## 已拒绝方案
+
+- **Windows `DnsServiceRegister`**:适合服务发现,但不能满足品牌主机名契约。
+- **Peach 自研 UDP 5353 别名响应器**:重复 zeroconf 已成熟实现,增加协议和共存风险。
+- **路由器静态 DNS**:会引入设备配置,并且把 `.local` 的 mDNS 语义混入单播 DNS。
+
+## 后果
+
+实现更短且恢复已知可用行为;多网卡主机可能发布到多个合格接口,但这正是本项目已验证的
+Windows 运行方式。若未来需要收窄接口,必须先新增真实客户端回归测试,不能由代码整洁性
+推导网络可用性。
diff --git a/src/peach/api.py b/src/peach/api.py
index 1f6f9cad4..2e1f0d097 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -104,6 +104,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:
"mdns": mdns.status if mdns is not None else "disabled",
"mdns_backend": mdns.backend if mdns is not None else None,
"mdns_service": mdns.name if mdns is not None else None,
+ "mdns_service_host": mdns.hostname if mdns is not None else None,
"mdns_address": mdns.address if mdns is not None else None,
"scheme": "https" if settings.tls_enabled else "http"}
diff --git a/src/peach/mdns.py b/src/peach/mdns.py
index 68dbf790a..faaaf562a 100644
--- a/src/peach/mdns.py
+++ b/src/peach/mdns.py
@@ -1,19 +1,13 @@
from __future__ import annotations
-import ctypes
-import os
import socket
-import struct
-import threading
from collections.abc import Callable
-from ctypes import wintypes
from zeroconf import ServiceInfo, Zeroconf
HTTP_SERVICE_TYPE = "_http._tcp.local."
HTTPS_SERVICE_TYPE = "_https._tcp.local."
-DNS_REQUEST_PENDING = 9506
def _normalized_name(name: str) -> str:
@@ -24,7 +18,7 @@ def _normalized_name(name: str) -> str:
def lan_ipv4() -> str:
- """Ask the local routing table for the preferred LAN IPv4 without sending data."""
+ """Ask the routing table for the preferred LAN IPv4 without sending data."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("192.0.2.1", 80))
@@ -33,21 +27,16 @@ def lan_ipv4() -> str:
sock.close()
-def lan_interface_index() -> int:
- """Return the interface Windows would use for the same LAN route as ``lan_ipv4``."""
- iphlpapi = ctypes.WinDLL("iphlpapi", use_last_error=True)
- iphlpapi.GetBestInterface.argtypes = [wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)]
- iphlpapi.GetBestInterface.restype = wintypes.DWORD
- destination = struct.unpack("<I", socket.inet_aton("192.0.2.1"))[0]
- index = wintypes.ULONG()
- result = int(iphlpapi.GetBestInterface(destination, ctypes.byref(index)))
- if result != 0:
- raise OSError(result, "GetBestInterface failed")
- return int(index.value)
+class MdnsPublisher:
+ """Publish Peach exactly like the verified pre-migration web server.
+ ``Zeroconf()`` deliberately listens on all eligible interfaces. Restricting it to
+ one IPv4 interface during the FastAPI migration made publication unreliable on
+ this Windows host, while Windows ``DnsServiceRegister`` advertised discovery but
+ could not create the branded ``peach.local`` host record.
+ """
-class MdnsPublisher:
- backend = "zeroconf"
+ backend = "zeroconf-all-interfaces"
def __init__(
self,
@@ -82,9 +71,9 @@ class MdnsPublisher:
properties={"path": "/", "scheme": "https" if self.secure else "http"},
server=f"{self.hostname}.",
)
- zeroconf = Zeroconf(interfaces=[address])
+ zeroconf = Zeroconf()
try:
- zeroconf.register_service(info, allow_name_change=False)
+ zeroconf.register_service(info, allow_name_change=True)
except Exception:
zeroconf.close()
raise
@@ -107,153 +96,5 @@ class MdnsPublisher:
self.status = "stopped"
-_REGISTER_COMPLETE = getattr(ctypes, "WINFUNCTYPE", ctypes.CFUNCTYPE)(
- None, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p,
-)
-
-
-class _DnsServiceRegisterRequest(ctypes.Structure):
- _fields_ = [
- ("Version", wintypes.ULONG),
- ("InterfaceIndex", wintypes.ULONG),
- ("pServiceInstance", ctypes.c_void_p),
- ("pRegisterCompletionCallback", _REGISTER_COMPLETE),
- ("pQueryContext", ctypes.c_void_p),
- ("hCredentials", wintypes.HANDLE),
- ("unicastEnabled", wintypes.BOOL),
- ]
-
-
-def _load_dnsapi():
- dnsapi = ctypes.WinDLL("dnsapi", use_last_error=True)
- dnsapi.DnsServiceConstructInstance.argtypes = [
- wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(wintypes.ULONG),
- ctypes.c_void_p, wintypes.WORD, wintypes.WORD, wintypes.WORD,
- wintypes.DWORD, ctypes.POINTER(wintypes.LPCWSTR),
- ctypes.POINTER(wintypes.LPCWSTR),
- ]
- dnsapi.DnsServiceConstructInstance.restype = ctypes.c_void_p
- dnsapi.DnsServiceRegister.argtypes = [
- ctypes.POINTER(_DnsServiceRegisterRequest), ctypes.c_void_p,
- ]
- dnsapi.DnsServiceRegister.restype = wintypes.DWORD
- dnsapi.DnsServiceDeRegister.argtypes = [
- ctypes.POINTER(_DnsServiceRegisterRequest), ctypes.c_void_p,
- ]
- dnsapi.DnsServiceDeRegister.restype = wintypes.DWORD
- dnsapi.DnsServiceFreeInstance.argtypes = [ctypes.c_void_p]
- dnsapi.DnsServiceFreeInstance.restype = None
- return dnsapi
-
-
-class WindowsMdnsPublisher:
- """Advertise through Windows DNS-SD instead of competing for UDP 5353.
-
- Windows DNS-SD registers a service instance; it does not create an arbitrary host
- alias. The SRV target therefore uses the actual Windows host name, while ``name``
- remains the user-facing service instance (``Peach``).
- """
-
- backend = "windows-dns-sd"
-
- def __init__(
- self,
- name: str,
- port: int,
- secure: bool = False,
- address_resolver: Callable[[], str] = lan_ipv4,
- dnsapi_factory: Callable[[], object] = _load_dnsapi,
- interface_resolver: Callable[[], int] = lan_interface_index,
- host_resolver: Callable[[], str] = socket.gethostname,
- ) -> None:
- self.name = _normalized_name(name)
- self.port = port
- self.secure = secure
- self._address_resolver = address_resolver
- self._dnsapi_factory = dnsapi_factory
- self._interface_resolver = interface_resolver
- self._host_resolver = host_resolver
- self.host_name = self._host_resolver().strip().removesuffix(".")
- self._dnsapi = None
- self._instance: int | None = None
- self._request: _DnsServiceRegisterRequest | None = None
- self._callback = None
- self._event = threading.Event()
- self._callback_status: int | None = None
- self.address: str | None = None
- self.status = "pending"
-
- @property
- def hostname(self) -> str:
- return f"{self.host_name}.local"
-
- def start(self) -> None:
- if self._request is not None:
- return
- address = self._address_resolver()
- dnsapi = self._dnsapi_factory()
- interface_index = self._interface_resolver()
- service = "_https._tcp.local" if self.secure else "_http._tcp.local"
- instance_name = f"{self.name}.{service}"
- ip4 = wintypes.ULONG.from_buffer_copy(socket.inet_aton(address))
- keys = (wintypes.LPCWSTR * 2)("path", "scheme")
- values = (wintypes.LPCWSTR * 2)("/", "https" if self.secure else "http")
- instance = dnsapi.DnsServiceConstructInstance(
- instance_name, self.host_name, ctypes.byref(ip4), None, self.port,
- 0, 0, 2, keys, values,
- )
- if not instance:
- raise OSError(ctypes.get_last_error(), "DnsServiceConstructInstance failed")
-
- self._event.clear()
- self._callback_status = None
-
- @_REGISTER_COMPLETE
- def completed(status, _context, callback_instance):
- self._callback_status = int(status)
- if callback_instance:
- dnsapi.DnsServiceFreeInstance(callback_instance)
- self._event.set()
-
- request = _DnsServiceRegisterRequest(
- 1, interface_index, instance, completed, None, None, False,
- )
- result = int(dnsapi.DnsServiceRegister(ctypes.byref(request), None))
- if result != DNS_REQUEST_PENDING:
- dnsapi.DnsServiceFreeInstance(instance)
- raise OSError(result, "DnsServiceRegister failed")
- if not self._event.wait(5) or self._callback_status != 0:
- dnsapi.DnsServiceDeRegister(ctypes.byref(request), None)
- dnsapi.DnsServiceFreeInstance(instance)
- raise OSError(self._callback_status or result, "mDNS registration did not complete")
- self._dnsapi = dnsapi
- self._instance = instance
- self._request = request
- self._callback = completed
- self.address = address
- self.status = self.hostname
-
- def stop(self) -> None:
- if self._request is None or self._dnsapi is None:
- return
- self._event.clear()
- try:
- result = int(self._dnsapi.DnsServiceDeRegister(
- ctypes.byref(self._request), None,
- ))
- if result == DNS_REQUEST_PENDING:
- self._event.wait(5)
- finally:
- if self._instance:
- self._dnsapi.DnsServiceFreeInstance(self._instance)
- self._dnsapi = None
- self._instance = None
- self._request = None
- self._callback = None
- self.address = None
- self.status = "stopped"
-
-
-def create_mdns_publisher(name: str, port: int, secure: bool = False):
- publisher_type = WindowsMdnsPublisher if os.name == "nt" else MdnsPublisher
- return publisher_type(name, port, secure=secure)
+def create_mdns_publisher(name: str, port: int, secure: bool = False) -> MdnsPublisher:
+ return MdnsPublisher(name, port, secure=secure)
diff --git a/tests/test_mdns.py b/tests/test_mdns.py
index e75e8e661..02bb25266 100644
--- a/tests/test_mdns.py
+++ b/tests/test_mdns.py
@@ -1,14 +1,11 @@
import unittest
from unittest.mock import patch
-from peach.mdns import (
- DNS_REQUEST_PENDING, MdnsPublisher, WindowsMdnsPublisher,
- create_mdns_publisher,
-)
+from peach.mdns import MdnsPublisher, create_mdns_publisher
class MdnsPublisherTests(unittest.TestCase):
- def test_registers_and_unregisters_peach_local(self):
+ def test_registers_and_unregisters_peach_local_on_all_interfaces(self):
with patch("peach.mdns.Zeroconf") as zeroconf_type:
publisher = MdnsPublisher(
"Peach.local", 80, address_resolver=lambda: "192.0.2.10"
@@ -18,8 +15,12 @@ class MdnsPublisherTests(unittest.TestCase):
self.assertEqual(info.server, "peach.local.")
self.assertEqual(info.port, 80)
self.assertEqual(publisher.status, "peach.local")
+ self.assertEqual(publisher.backend, "zeroconf-all-interfaces")
publisher.stop()
- zeroconf_type.assert_called_once_with(interfaces=["192.0.2.10"])
+ zeroconf_type.assert_called_once_with()
+ zeroconf_type.return_value.register_service.assert_called_once_with(
+ info, allow_name_change=True,
+ )
zeroconf_type.return_value.unregister_service.assert_called_once_with(info)
zeroconf_type.return_value.close.assert_called_once()
@@ -38,44 +39,8 @@ class MdnsPublisherTests(unittest.TestCase):
with self.assertRaises(ValueError):
MdnsPublisher("bad name", 80)
- def test_windows_native_registration_lifecycle(self):
- class Function:
- def __init__(self, action=None, result=None):
- self.action = action
- self.result = result
-
- def __call__(self, *args):
- return self.action(*args) if self.action else self.result
-
- class DnsApi:
- def __init__(self):
- self.DnsServiceConstructInstance = Function(result=123)
- self.DnsServiceFreeInstance = Function()
- self.DnsServiceRegister = Function(self._complete)
- self.DnsServiceDeRegister = Function(self._complete)
-
- @staticmethod
- def _complete(request_pointer, _cancel):
- request_pointer._obj.pRegisterCompletionCallback(0, None, None)
- return DNS_REQUEST_PENDING
-
- dnsapi = DnsApi()
- publisher = WindowsMdnsPublisher(
- "peach", 80, address_resolver=lambda: "192.0.2.10",
- dnsapi_factory=lambda: dnsapi,
- interface_resolver=lambda: 9, host_resolver=lambda: "LMD-DST",
- )
- publisher.start()
- self.assertEqual(publisher.status, "LMD-DST.local")
- self.assertEqual(publisher.backend, "windows-dns-sd")
- self.assertEqual(publisher._request.InterfaceIndex, 9)
- self.assertEqual(publisher.hostname, "LMD-DST.local")
- publisher.stop()
- self.assertEqual(publisher.status, "stopped")
-
- @patch("peach.mdns.os.name", "nt")
- def test_factory_uses_windows_native_backend(self):
- self.assertIsInstance(create_mdns_publisher("peach", 80), WindowsMdnsPublisher)
+ def test_factory_uses_verified_zeroconf_backend(self):
+ self.assertIsInstance(create_mdns_publisher("peach", 80), MdnsPublisher)
if __name__ == "__main__":