Files
o2o-castad-backend/app/p2v/worker/worker.py
T
skkim 50899861d0 fix: 단독 P2V 워커가 모델 미등록으로 큐를 처리하지 못하던 문제 수정
- standalone 이 main 을 import 하지 않아 첫 DB 조회에서 매퍼 설정 오류가 나고,
  loop() 의 requeue_running 이 try 밖이라 워커 태스크만 조용히 죽던 문제
- standalone 이 모델을 직접 등록하고, 워커 루프가 예기치 않게 끝나면 프로세스도 비정상 종료(restart 로 복구)
- 기동 시 requeue_running 실패를 재시도하도록 loop 보강, start() 가 태스크를 반환
2026-10-15 14:35:09 +09:00

89 lines
3.0 KiB
Python

"""queued 잡을 하나씩 집어 다음 게이트까지 돌리는 배경 실행기
큐가 DB에 있어 동시 실행 수를 올리거나 컨테이너를 늘려도 파이프라인 코드는 그대로
승인이 status를 queued로 되돌리면 다음 폴링에서 이어 감
"""
import asyncio
import traceback
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.p2v.worker.runner import QUEUED, RUNNING, run_until_gate
from app.p2v.models import PlayreelTask, PosterAliveTask
from app.database.session import BackgroundSessionLocal
POLL_INTERVAL = 2.0
TABLES = (PlayreelTask, PosterAliveTask)
_worker: asyncio.Task | None = None
async def claim_next(session: AsyncSession):
"""queued 잡 하나를 running으로 바꿔 가져온다
워커가 하나인 동안은 경합이 없다. 늘릴 때 SELECT ... FOR UPDATE SKIP LOCKED로 바꾼다
"""
for table in TABLES:
found = await session.scalars(
select(table).where(table.status == QUEUED)
.order_by(table.created_at).limit(1))
task = found.first()
if task is not None:
task.status = RUNNING
await session.commit()
return task
return None
async def run_once() -> bool:
async with BackgroundSessionLocal() as session:
task = await claim_next(session)
if task is None:
return False
await run_until_gate(session, task)
return True
async def requeue_running() -> None:
"""기동 시 running으로 남은 잡을 되살린다 — 어디까지 갔는지는 state가 기억한다"""
async with BackgroundSessionLocal() as session:
for table in TABLES:
for task in await session.scalars(select(table).where(table.status == RUNNING)):
task.status = QUEUED
await session.commit()
async def loop() -> None:
# 기동 시 일시적인 오류(DB 연결 등)로 워커가 조용히 죽지 않게, 성공할 때까지 재시도한다.
# 이 줄이 try 밖에 있으면 예외 하나로 태스크만 죽고 프로세스는 살아 있어 큐가 멈춘다
while True:
try:
await requeue_running()
break
except asyncio.CancelledError:
raise
except Exception:
traceback.print_exc()
await asyncio.sleep(POLL_INTERVAL)
while True:
try:
if not await run_once():
await asyncio.sleep(POLL_INTERVAL)
except asyncio.CancelledError:
raise
except Exception:
# 워커는 죽지 않는다. DB가 끊긴 경우라 잠시 쉬고 다시 본다
traceback.print_exc()
await asyncio.sleep(POLL_INTERVAL)
def start() -> asyncio.Task:
global _worker
_worker = asyncio.create_task(loop(), name="pipeline-worker")
return _worker
async def stop() -> None:
if _worker is not None:
_worker.cancel()
await asyncio.gather(_worker, return_exceptions=True)