fix: guard pool initialization with asyncio.Lock to prevent race condition

This commit is contained in:
counterweight 2025-12-21 23:23:21 +01:00
parent b33e5e425a
commit 027a6fb64c
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C

View file

@ -1,5 +1,6 @@
"""Job definitions and enqueueing utilities using pgqueuer."""
import asyncio
import json
import asyncpg
@ -12,13 +13,20 @@ JOB_RANDOM_NUMBER = "random_number"
# Connection pool for job enqueueing (lazy initialized)
_pool: asyncpg.Pool | None = None
_pool_lock = asyncio.Lock()
async def get_job_pool() -> asyncpg.Pool:
"""Get or create the connection pool for job enqueueing."""
global _pool
if _pool is not None:
return _pool
async with _pool_lock:
# Double-check after acquiring lock
if _pool is None:
_pool = await asyncpg.create_pool(ASYNCPG_DATABASE_URL, min_size=1, max_size=5)
_pool = await asyncpg.create_pool(
ASYNCPG_DATABASE_URL, min_size=1, max_size=5
)
return _pool