Fix Ghost sync race: advisory lock for multi-worker startup
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m0s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m0s
Two Hypercorn workers both run sync_all_content_from_ghost on startup, racing on PostAuthor/PostTag rows. Use pg_try_advisory_lock so only one worker runs the sync. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -48,10 +48,20 @@ def register(url_prefix, title):
|
|||||||
@blogs_bp.before_app_serving
|
@blogs_bp.before_app_serving
|
||||||
async def init():
|
async def init():
|
||||||
from .ghost.ghost_sync import sync_all_content_from_ghost
|
from .ghost.ghost_sync import sync_all_content_from_ghost
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
# Advisory lock prevents multiple Hypercorn workers from
|
||||||
|
# running the sync concurrently (which causes PK conflicts).
|
||||||
async with get_session() as s:
|
async with get_session() as s:
|
||||||
await sync_all_content_from_ghost(s)
|
got_lock = await s.scalar(text("SELECT pg_try_advisory_lock(900001)"))
|
||||||
await s.commit()
|
if not got_lock:
|
||||||
|
return # another worker is syncing
|
||||||
|
try:
|
||||||
|
await sync_all_content_from_ghost(s)
|
||||||
|
await s.commit()
|
||||||
|
finally:
|
||||||
|
await s.execute(text("SELECT pg_advisory_unlock(900001)"))
|
||||||
|
await s.commit()
|
||||||
|
|
||||||
@blogs_bp.before_request
|
@blogs_bp.before_request
|
||||||
def route():
|
def route():
|
||||||
|
|||||||
Reference in New Issue
Block a user