Files
skkim 608ef36848 feat: 썰박스 생성을 DB 대기열과 단독 러너로 전환
- API는 잡을 queued 로 DB에 남기기만 하고(request_params 컬럼에 입력 저장), 단독 실행 락을 잡은 러너 한 프로세스가 오래된 순서로 가져가 처리한다
- 동시 실행 한도가 전체 기준이 되고, 자리가 없으면 queued 로 대기했다가 앞 잡이 끝나면 시작한다
- 고아 정리(sweep_orphans)는 락을 잡은 직후 running 만 대상으로 한다. 다른 프로세스의 정상 잡을 환불·error 처리하던 문제 해결
- 이미 error(환불됨)인 잡이 완료로 되살아나 영상과 환불을 모두 얻는 경로 차단
- SSULBOX_WORKER_ENABLED 로 웹 프로세스 내 러너(락 경쟁)와 전용 컨테이너(python -m app.ssulbox.worker.standalone)를 선택한다
- 마이그레이션: migration_2026-10-15_ssul_runner.sql (코드 배포 전에 실행)
2026-10-15 16:43:29 +09:00

140 lines
6.1 KiB
Python

"""썰박스 생성 러너 — DB 대기열(queued)을 순서대로 가져가 생성한다.
- **DB 가 대기열이다.** API 는 잡을 queued 로 남기기만 한다. 러너가 동시 한도(`SSULBOX_MAX_CONCURRENT_JOBS`)
안에서 가장 오래된 잡부터 가져가고, 자리가 없으면 잡은 **queued 로 기다렸다가** 앞 잡이 끝나면 시작한다.
- **러너는 한 프로세스만 일한다.** 시작하면 단독 실행 락(MySQL `GET_LOCK`)을 잡고, 이미 다른 러너가 쥐고
있으면 그 러너가 끝날 때까지 **대기**한다. 락을 잡기 전에는 고아 정리도 하지 않으므로, 먼저 돌던 러너의
잡을 건드리지 않는다. 한도는 한 프로세스의 것이라 **전체 기준**이 된다.
- 고아 정리(`sweep_orphans`)는 락을 잡은 직후 **running 만** 대상으로 한다(이전 러너가 남긴 것).
queued 는 대기열의 정상 잡이다.
- 락을 잃으면(DB 연결 끊김 등) 실행 중인 생성을 즉시 모두 멈춘다. 다른 러너가 시작해 이쪽의 running 을
고아로 정리하기 때문에, 이쪽이 계속 생성하면 같은 잡이 이중으로 돈다.
사용: 전용 프로세스 `python -m app.ssulbox.worker.standalone`, 또는 웹 프로세스 안에서(`SSULBOX_WORKER_ENABLED`)
`run_forever`. 웹 워커가 여럿이어도 락 덕분에 하나만 일하고 나머지는 대기하다가 이어받는다.
"""
import asyncio
import traceback
from typing import Awaitable, Callable, Optional
from app.database.session import BackgroundSessionLocal
from app.ssulbox.services import task_service
from app.ssulbox.worker import job_manager
from app.utils.logger import get_logger
from app.utils.singleton_lock import LockLost, SingletonLock
logger = get_logger("ssulbox")
LOCK_NAME = "ssul-runner"
#: 대기열 조회 간격, 락 대기 재시도 간격, 락 보유 확인 간격(초)
POLL_SECONDS = 2.0
LOCK_POLL_SECONDS = 3.0
LOCK_WATCH_SECONDS = 10.0
OnAcquired = Callable[[], Awaitable[None]]
async def _fail(content_id: int, error: str) -> None:
async with BackgroundSessionLocal() as session:
try:
await task_service.fail_task(session, content_id, error)
await session.commit()
except Exception:
await session.rollback()
raise
async def claim_and_enqueue() -> int:
"""자리가 있으면 DB 대기열에서 가져와 실행 큐에 넣는다. 시작한 잡 수를 돌려준다."""
free = job_manager.capacity()
if free <= 0:
return 0
async with BackgroundSessionLocal() as session:
try:
rows = await task_service.claim_queued(session, free)
await session.commit()
except Exception:
await session.rollback()
raise
started = 0
for row in rows:
if job_manager.enqueue_from_row(row):
started += 1
else:
# 입력이 없어 실행할 수 없다(이 방식으로 바뀌기 전에 큐잉된 잡). 환불하고 닫는다
logger.error(f"[runner] 생성 입력 없음 id={row.id} — 실패 처리")
await _fail(row.id, "생성 입력 정보가 없어 실행할 수 없습니다")
return started
async def _poll_loop(stop: asyncio.Event) -> None:
while not stop.is_set():
try:
await claim_and_enqueue()
except asyncio.CancelledError:
raise
except Exception:
# DB 일시 오류로 러너가 죽지 않는다. 잠시 쉬고 다시 본다
traceback.print_exc()
try:
await asyncio.wait_for(stop.wait(), timeout=POLL_SECONDS)
except asyncio.TimeoutError:
pass
async def _serve(lock: SingletonLock, stop: asyncio.Event, on_acquired: Optional[OnAcquired]) -> None:
job_manager.bind_loop(asyncio.get_running_loop())
if on_acquired is not None:
await on_acquired()
# 락을 잡은 직후다 — 이 시점의 running 은 전부 이전 러너가 남긴 고아다
async with BackgroundSessionLocal() as session:
swept = await task_service.sweep_orphans(session)
await session.commit()
logger.info(f"[runner] 시작 — 고아 {swept}건 정리, 동시 한도 우선 대기열부터 처리")
poller = asyncio.ensure_future(_poll_loop(stop))
watcher = asyncio.ensure_future(lock.watch(LOCK_WATCH_SECONDS))
stopper = asyncio.ensure_future(stop.wait())
try:
done, _ = await asyncio.wait({poller, watcher, stopper}, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if task is not stopper:
task.result() # 락 상실(LockLost)이나 루프 예외면 여기서 올라간다
finally:
for task in (poller, watcher, stopper):
task.cancel()
# 멈추거나 락을 잃은 시점부터는 이 프로세스가 생성을 이어가면 안 된다
killed = job_manager.abort_all()
if killed:
logger.warning(f"[runner] 실행 중이던 생성 {killed}건 중단 (다음 러너가 정리·환불)")
async def run_runner(stop: asyncio.Event, *, on_acquired: Optional[OnAcquired] = None) -> None:
"""락을 잡을 때까지 기다린 뒤 stop 이 켜질 때까지 대기열을 처리한다. 락을 잃으면 LockLost."""
lock = SingletonLock(LOCK_NAME, poll_seconds=LOCK_POLL_SECONDS)
logger.info("[runner] 실행 락 대기")
if not await lock.acquire(stop):
logger.info("[runner] 락을 잡기 전에 종료")
return
try:
await _serve(lock, stop, on_acquired)
finally:
await lock.release()
logger.info("[runner] 종료")
async def run_forever(stop: asyncio.Event) -> None:
"""웹 프로세스 안에서 쓰는 러너. 락을 잃으면 멈추고 다시 락을 기다린다(프로세스는 계속 API 를 한다)."""
while not stop.is_set():
try:
await run_runner(stop)
except asyncio.CancelledError:
raise
except LockLost as e:
logger.error(f"[runner] {e} — 생성 중단, 다시 락을 기다린다")
await asyncio.sleep(1)
except Exception:
traceback.print_exc()
await asyncio.sleep(5)