ref: make superuser creation more multi-user friendly (#9019)

* Fix superuser creationg race condition

* remove now unnecessary race condition check

* Add tests

* [autofix.ci] apply automated fixes

* ruff

* [autofix.ci] apply automated fixes

* clean up tests

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
Jordan Frazier 2025-07-23 11:45:03 -07:00 • committed by GitHub
commit 115b0f535f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 129 additions and 15 deletions

View file

@ -454,7 +454,7 @@ class MCPToolsComponent(ComponentWithCache):
kwargs = {}
for arg in tool_args:
value = getattr(self, arg.name, None)
if value:
if value is not None:
if isinstance(value, Message):
kwargs[arg.name] = value.text
else:

File diff suppressed because one or more lines are too long

View file

@ -11,6 +11,7 @@ from fastapi import Depends, HTTPException, Security, WebSocketException, status
from fastapi.security import APIKeyHeader, APIKeyQuery, OAuth2PasswordBearer
from jose import JWTError, jwt
from loguru import logger
from sqlalchemy.exc import IntegrityError
from sqlmodel.ext.asyncio.session import AsyncSession
from starlette.websockets import WebSocket
@ -299,8 +300,17 @@ async def create_super_user(
)
db.add(super_user)
await db.commit()
await db.refresh(super_user)
try:
await db.commit()
await db.refresh(super_user)
except IntegrityError:
# Race condition - another worker created the user
await db.rollback()
super_user = await get_user_by_username(db, username)
if not super_user:
raise # Re-raise if it's not a race condition
except Exception: # noqa: BLE001
logger.opt(exception=True).debug("Error creating superuser.")
return super_user

View file

@ -65,16 +65,7 @@ async def get_or_create_super_user(session: AsyncSession, username, password, is
logger.debug("Creating default superuser.")
else:
logger.debug("Creating superuser.")
try:
return await create_super_user(username, password, db=session)
except Exception as exc: # noqa: BLE001
if "UNIQUE constraint failed: user.username" in str(exc):
# This is to deal with workers running this
# at startup and trying to create the superuser
# at the same time.
logger.opt(exception=True).debug("Superuser already exists.")
return None
logger.opt(exception=True).debug("Error creating superuser.")
return await create_super_user(username, password, db=session)
async def setup_superuser(settings_service, session: AsyncSession) -> None: