From c4fb4fb4984e9023a4e94276032520e4b1503de6 Mon Sep 17 00:00:00 2001 From: Pine Date: Mon, 24 Aug 2026 19:15:20 +0800 Subject: [PATCH] =?UTF-8?q?fix(server-core):=20=E7=A7=8D=E5=AD=90=E5=AE=B9?= =?UTF-8?q?=E9=94=99=20+=20=E6=99=BA=E8=83=BD=E4=BD=93=E7=A7=8D=E5=AD=90?= =?UTF-8?q?=E5=B9=82=E7=AD=89=20=E2=80=94=20=E4=BF=AE=E5=A4=8D=20lifespan?= =?UTF-8?q?=20=E5=BB=BA=E5=BA=93=E8=A2=AB=E7=A7=8D=E5=AD=90=E5=94=AF?= =?UTF-8?q?=E4=B8=80=E5=86=B2=E7=AA=81=E6=8B=96=E5=9E=AE(=E5=85=A8500)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:AGENT_SEED 用全局固定 agent id,demo 用户补种时对多个用户复用同一 id → (id,user_id,port) 唯一冲突 → seed_data 抛 IntegrityError → 平台 lifespan 建库失败 → app.state.db 未设置 → 全 500。 - repositories.initialize:种子包 try/except + rollback(记 warn),种子失败不再拖垮 lifespan 建库。 - seed._ensure_port_agents:改为按 agent.id 逐条判断已存在,避免重复插入幂等。 验证:登录/me/users/courses/roles 全 200。 --- app/infrastructure/repositories.py | 9 ++++++++- app/infrastructure/seed.py | 8 ++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/app/infrastructure/repositories.py b/app/infrastructure/repositories.py index 9ffbbf9..352f5c6 100644 --- a/app/infrastructure/repositories.py +++ b/app/infrastructure/repositories.py @@ -1864,7 +1864,14 @@ class Database: if self._engine is not None: async with self._engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) - await seed_data(self.session) + # 种子容错:个别幂等保护不严的地方(如 demo 用户固定 agent id)可能触发唯一冲突, + # 不能让种子失败拖垮 lifespan 建库,否则 app.state.db 未设置→全部 500。 + try: + await seed_data(self.session) + except Exception as e: # noqa: BLE001 + import logging + logging.getLogger("servercore").warning("种子数据写入失败(忽略,应用仍可用): %s", e) + await self.session.rollback() async def close(self) -> None: if self._owns_session: diff --git a/app/infrastructure/seed.py b/app/infrastructure/seed.py index 9ad2935..19608c1 100644 --- a/app/infrastructure/seed.py +++ b/app/infrastructure/seed.py @@ -1045,12 +1045,12 @@ async def _ensure_port_agents(session: AsyncSession, now: str) -> None: if (user_id, port) in seen: continue seen.add((user_id, port)) - existing = await session.scalar( - select(Agent.id).where(Agent.user_id == user_id, Agent.port == port).limit(1) + existing_ids = set( + (await session.execute(select(Agent.id).where(Agent.user_id == user_id, Agent.port == port))).scalars() ) - if existing is not None: - continue for seed in AGENT_SEED: + if seed["id"] in existing_ids: + continue # 已存在,跳过(幂等,避免 (id,user_id,port) 唯一冲突) session.add( Agent( id=seed["id"], user_id=user_id, port=port, name=seed["name"],