fix: add collision retry for userid generation
This commit is contained in:
parent
e4e484dc4b
commit
9d7a67b2d2
2 changed files with 60 additions and 1 deletions
|
|
@ -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")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue