fix: add collision retry for userid generation

This commit is contained in:
Johan Lundberg 2026-02-12 15:34:31 +01:00
parent e4e484dc4b
commit 9d7a67b2d2
No known key found for this signature in database
GPG key ID: A6C152738D03C7D1
2 changed files with 60 additions and 1 deletions

View file

@ -2,6 +2,8 @@ import secrets
from proquint import uint2quint
from fastapi_oidc_op.store.protocols import UserRepository
def generate_userid() -> str:
"""Generate a unique user identifier in proquint format.
@ -9,3 +11,17 @@ def generate_userid() -> str:
Returns a 32-bit proquint string like 'lusab-bansen'.
"""
return uint2quint(secrets.randbits(32))
async def generate_unique_userid(user_repo: UserRepository, max_retries: int = 10) -> str:
"""Generate a userid that does not already exist in the repository.
Calls generate_userid() and checks for collisions via user_repo.get_by_userid().
Retries up to max_retries times before raising RuntimeError.
"""
for _ in range(max_retries):
candidate = generate_userid()
existing = await user_repo.get_by_userid(candidate)
if existing is None:
return candidate
raise RuntimeError(f"Failed to generate unique userid after {max_retries} retries")