fix: Registry 审查修复(JSON定位/校验测试/竞态窗口/TenantDisabledError/路径锚定/seed_dir)
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+194
-5
@@ -1,23 +1,56 @@
|
||||
"""TenantRegistry 单元契约(Task 5a 文件加载器)。
|
||||
"""TenantRegistry 单元契约(Task 5a 文件加载器 + 审查修复)。
|
||||
|
||||
seed_profiles/<slug>/tenant.json + 同目录 wall.json → Registry;
|
||||
Host(小写/去端口)→站点→租户;首次 resolve 懒建 engine(WAL/pool=2)+
|
||||
ensure_schema;reload 原子换条目并 dispose 旧 engine。
|
||||
ensure_schema;reload 原子换条目并 dispose 旧 engine;停用租户
|
||||
TenantDisabledError(503 语义);加载期校验显性炸。
|
||||
|
||||
Windows 纪律:每个建过 engine 的用例结尾 await reg.dispose_all()——
|
||||
连接不关,文件锁着,tmp_path 清理 PermissionError。
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import app.platform.registry as registry_mod
|
||||
from app.platform.registry import (
|
||||
TenantDisabledError,
|
||||
TenantRegistry,
|
||||
UnknownTenantError,
|
||||
make_tenant_engine,
|
||||
)
|
||||
|
||||
SEED_DIR = "seed_profiles"
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
SEED_DIR = REPO_ROOT / "seed_profiles"
|
||||
|
||||
|
||||
def _tenant(slug, domains=("a.example.com",), **extra):
|
||||
"""最小合法 tenant.json(dict 形态);extra 覆盖顶层键。"""
|
||||
tenant = {"slug": slug, "name": slug, "status": "active",
|
||||
"sites": [{"slug": "main", "domains": list(domains)}],
|
||||
"config": {}}
|
||||
tenant.update(extra)
|
||||
return tenant
|
||||
|
||||
|
||||
def _write_seed(tmp_path, tenants):
|
||||
"""tmp 下造最小 seed 目录:每租户目录 = 入参 tenant.json + 拷贝真实
|
||||
jiancai wall.json(墙数据不重复维护,compile_wall 直接可过)。"""
|
||||
seed = tmp_path / "seed"
|
||||
seed.mkdir()
|
||||
for slug, tenant in tenants.items():
|
||||
tdir = seed / slug
|
||||
tdir.mkdir()
|
||||
shutil.copyfile(SEED_DIR / "jiancai" / "wall.json", tdir / "wall.json")
|
||||
(tdir / "tenant.json").write_text(
|
||||
json.dumps(tenant, ensure_ascii=False), encoding="utf-8")
|
||||
return seed
|
||||
|
||||
|
||||
# ---- 基础解析 -------------------------------------------------------------
|
||||
|
||||
|
||||
async def test_resolve_by_host(tmp_path):
|
||||
@@ -74,8 +107,6 @@ async def test_host_normalization_case_and_port(tmp_path):
|
||||
|
||||
async def test_concurrent_first_resolve_builds_engine_once(tmp_path, monkeypatch):
|
||||
"""两个协程同时首 resolve 同一租户:engine 只建一次(asyncio.Lock 串行)。"""
|
||||
import app.platform.registry as registry_mod
|
||||
|
||||
calls = []
|
||||
real_make = registry_mod.make_tenant_engine
|
||||
|
||||
@@ -105,3 +136,161 @@ async def test_make_tenant_engine_enables_wal(tmp_path):
|
||||
assert str(mode).lower() == "wal"
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
# ---- 加载期校验(I-4) ------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_empty_seed_dir_raises(tmp_path):
|
||||
seed = tmp_path / "seed"
|
||||
seed.mkdir()
|
||||
with pytest.raises(ValueError, match="没有任何"):
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
|
||||
|
||||
def test_load_invalid_json_raises_with_path(tmp_path):
|
||||
"""坏 JSON 必须带文件路径显性炸(哪份文件坏了一目了然)。"""
|
||||
seed = tmp_path / "seed"
|
||||
(seed / "jiancai").mkdir(parents=True)
|
||||
(seed / "jiancai" / "tenant.json").write_text("{oops", encoding="utf-8")
|
||||
with pytest.raises(ValueError, match=r"tenant\.json.*无效 JSON"):
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
|
||||
|
||||
def test_load_slug_dir_mismatch_raises(tmp_path):
|
||||
seed = _write_seed(tmp_path, {"dirslug": _tenant("jsonslug")})
|
||||
with pytest.raises(ValueError, match="不一致"):
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
|
||||
|
||||
def test_load_zero_sites_raises(tmp_path):
|
||||
tenant = _tenant("jiancai")
|
||||
tenant["sites"] = []
|
||||
seed = _write_seed(tmp_path, {"jiancai": tenant})
|
||||
with pytest.raises(ValueError, match="至少一个站点"):
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
|
||||
|
||||
def test_load_domain_conflict_across_tenants_raises(tmp_path):
|
||||
seed = _write_seed(tmp_path, {
|
||||
"t1": _tenant("t1", ["dup.example.com"]),
|
||||
"t2": _tenant("t2", ["dup.example.com"])})
|
||||
with pytest.raises(ValueError, match="dup.example.com"):
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
|
||||
|
||||
def test_load_domain_conflict_within_tenant_raises(tmp_path):
|
||||
"""同租户两个站点抢同一域名也要炸,报错含双方 (tenant, site)。"""
|
||||
tenant = _tenant("t1", ["dup.example.com"])
|
||||
tenant["sites"].append({"slug": "second", "domains": ["dup.example.com"]})
|
||||
seed = _write_seed(tmp_path, {"t1": tenant})
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
msg = str(excinfo.value)
|
||||
assert "main" in msg and "second" in msg and "t1" in msg
|
||||
|
||||
|
||||
# ---- reload / dispose 行为 -------------------------------------------------
|
||||
|
||||
|
||||
async def test_reload_bad_config_keeps_old_entry_serving(tmp_path):
|
||||
"""reload 遇坏配置必须先炸后不动:旧条目(含域名索引)原样服务。"""
|
||||
tenant = _tenant("jiancai", ["a.example.com"])
|
||||
tenant["config"] = {"push": {"prefix": "v1"}}
|
||||
seed = _write_seed(tmp_path, {"jiancai": tenant})
|
||||
reg = TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
rt1 = await reg.resolve("a.example.com")
|
||||
assert rt1.config.data["push"]["prefix"] == "v1"
|
||||
|
||||
tenant["sites"] = [] # 改坏:零站点
|
||||
(seed / "jiancai" / "tenant.json").write_text(
|
||||
json.dumps(tenant, ensure_ascii=False), encoding="utf-8")
|
||||
with pytest.raises(ValueError, match="至少一个站点"):
|
||||
await reg.registry_reload("jiancai")
|
||||
|
||||
rt = await reg.resolve("a.example.com") # 旧条目继续服务
|
||||
assert rt is rt1 and rt.config.data["push"]["prefix"] == "v1"
|
||||
await reg.dispose_all()
|
||||
|
||||
|
||||
async def test_dispose_all_then_resolve_rebuilds(tmp_path):
|
||||
"""dispose_all 复位为未就绪,再 resolve 重新懒建(可安全复用)。"""
|
||||
reg = TenantRegistry.load_from_dir(SEED_DIR, data_dir=tmp_path)
|
||||
rt = await reg.resolve("chat2.agent.hnxinyouhe.com")
|
||||
engine_before = rt.engine
|
||||
await reg.dispose_all()
|
||||
assert rt.engine is None
|
||||
rt2 = await reg.resolve("chat2.agent.hnxinyouhe.com")
|
||||
assert rt2 is rt
|
||||
assert rt2.engine is not None and rt2.engine is not engine_before
|
||||
await reg.dispose_all()
|
||||
|
||||
|
||||
async def test_resolve_waiting_through_reload_serves_new_entry(tmp_path):
|
||||
"""I-2 竞态:resolve 排队等锁期间条目被 reload 换掉——持锁后现势
|
||||
检查必须放弃旧 runtime 按新条目建库(旧 runtime 永不产生孤儿 engine)。
|
||||
|
||||
构造:测试占住 per-slug 锁 → reload 与 resolve 先后排到锁等待
|
||||
(FIFO:reload 先拿锁换条目)→ 释放后 resolve 持锁发现条目已换。
|
||||
"""
|
||||
reg = TenantRegistry.load_from_dir(SEED_DIR, data_dir=tmp_path)
|
||||
rt_old = reg._by_slug["jiancai"] # 单元测试:直查内部状态
|
||||
lock = reg._locks.setdefault("jiancai", asyncio.Lock())
|
||||
async with lock:
|
||||
reloader = asyncio.create_task(reg.registry_reload("jiancai"))
|
||||
resolver = asyncio.create_task(reg.resolve("chat2.agent.hnxinyouhe.com"))
|
||||
await asyncio.sleep(0) # 两任务均跑到锁等待
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.gather(reloader, resolver)
|
||||
|
||||
rt = resolver.result()
|
||||
assert rt is reg._by_slug["jiancai"] # 服务 reload 后的新条目
|
||||
assert rt is not rt_old
|
||||
assert rt_old.engine is None # 旧 runtime 没被建库(无孤儿句柄)
|
||||
assert rt.engine is not None
|
||||
await reg.dispose_all()
|
||||
|
||||
|
||||
# ---- 停用租户(I-3) ---------------------------------------------------------
|
||||
|
||||
|
||||
async def test_disabled_tenant_resolve_raises_and_never_builds_engine(
|
||||
tmp_path, monkeypatch):
|
||||
"""status=disabled:resolve 抛 TenantDisabledError(503 语义,非 404),
|
||||
且从不建 engine。"""
|
||||
calls = []
|
||||
real_make = registry_mod.make_tenant_engine
|
||||
|
||||
def counting_make(db_path):
|
||||
calls.append(db_path)
|
||||
return real_make(db_path)
|
||||
|
||||
monkeypatch.setattr(registry_mod, "make_tenant_engine", counting_make)
|
||||
|
||||
seed = _write_seed(tmp_path, {"jiancai": _tenant("jiancai", status="disabled")})
|
||||
reg = TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
with pytest.raises(TenantDisabledError):
|
||||
await reg.resolve("a.example.com")
|
||||
with pytest.raises(TenantDisabledError): # 再 resolve 同样拒绝
|
||||
await reg.resolve("a.example.com")
|
||||
assert calls == [] # 从未建 engine
|
||||
await reg.dispose_all()
|
||||
|
||||
|
||||
async def test_reload_to_disabled_releases_engine(tmp_path):
|
||||
"""active→disabled 热切换:旧 engine 随 reload dispose,resolve 转抛。"""
|
||||
tenant = _tenant("jiancai", ["a.example.com"])
|
||||
seed = _write_seed(tmp_path, {"jiancai": tenant})
|
||||
reg = TenantRegistry.load_from_dir(seed, data_dir=tmp_path / "data")
|
||||
rt1 = await reg.resolve("a.example.com")
|
||||
assert rt1.engine is not None
|
||||
|
||||
tenant["status"] = "disabled"
|
||||
(seed / "jiancai" / "tenant.json").write_text(
|
||||
json.dumps(tenant, ensure_ascii=False), encoding="utf-8")
|
||||
await reg.registry_reload("jiancai")
|
||||
|
||||
assert rt1.engine is None # 旧 engine 已释放
|
||||
with pytest.raises(TenantDisabledError):
|
||||
await reg.resolve("a.example.com")
|
||||
await reg.dispose_all()
|
||||
|
||||
Reference in New Issue
Block a user