modify: auth插件拆分,将token签发部分交给网关
This commit is contained in:
+11
-25
@@ -1,37 +1,25 @@
|
||||
"""
|
||||
并发启动竞态测试:模拟 gunicorn 多 worker 同时启动时,
|
||||
多个进程并发调用 plugins.auth.create_workers 初始化默认管理员。
|
||||
多个进程并发执行网关内置的 admin 种子(chongming_auth.seed_admin)。
|
||||
|
||||
auth 域拆分后,admin 种子从 plugins.auth 的 on_init 迁移到网关
|
||||
lifespan(setup_auth_store → chongming_auth.seed_admin),本测试随之改指向。
|
||||
|
||||
预期:不抛 IntegrityError,users 表中只有一条 admin 记录。
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent / "src"))
|
||||
|
||||
import plugins.auth as auth_plugin
|
||||
|
||||
|
||||
def fake_create_workers(session, config, count=1, worker_manager=None):
|
||||
"""替换真实 worker 启动,避免依赖 zenoh 会话。与原始实现同为同步函数。"""
|
||||
return []
|
||||
from chongming_auth import open_database, seed_admin
|
||||
|
||||
|
||||
async def main():
|
||||
# 替换 Plugin 基类的 worker 创建实现,避免依赖 zenoh 会话
|
||||
auth_plugin.plugin._create_workers_impl = fake_create_workers
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = {"type": "auth", "data_dir": tmp}
|
||||
db = await open_database({"data_dir": tmp})
|
||||
|
||||
# 模拟 4 个 gunicorn worker 进程同时启动
|
||||
results = await asyncio.gather(
|
||||
auth_plugin.create_workers(None, config, 3),
|
||||
auth_plugin.create_workers(None, config, 3),
|
||||
auth_plugin.create_workers(None, config, 3),
|
||||
auth_plugin.create_workers(None, config, 3),
|
||||
*[seed_admin(db) for _ in range(4)],
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
@@ -42,15 +30,11 @@ async def main():
|
||||
raise RuntimeError("并发启动存在未捕获异常")
|
||||
|
||||
# 校验 users 表中应只有一条 admin
|
||||
from chongming_database import Database
|
||||
from plugins.auth.models.auth import Users
|
||||
from chongming_auth import Users
|
||||
from sqlalchemy import select
|
||||
|
||||
db = Database(Path(tmp) / "auth.db")
|
||||
await db.initialize()
|
||||
async with db.get_session() as sess:
|
||||
res = await sess.execute(select(Users))
|
||||
rows = res.scalars().all()
|
||||
rows = (await sess.execute(select(Users))).scalars().all()
|
||||
|
||||
print("✅ 4 个并发启动全部成功")
|
||||
print(f"✅ users 表记录数: {len(rows)}(应为 1)")
|
||||
@@ -58,6 +42,8 @@ async def main():
|
||||
print(f" - {u.username} <{u.email}> superuser={u.is_superuser}")
|
||||
|
||||
assert len(rows) == 1, f"预期 1 条 admin,实际 {len(rows)} 条"
|
||||
assert sum(1 for r in results if r is True) == 1, "应恰好一个并发方完成新建"
|
||||
await db.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user