feat: p2v 연동

This commit is contained in:
skkim committed 2026-08-26 13:52:18 +09:00
1 parent b3385e7df2
commit 5de5c7507d
26 files changed
+2944 -9

No files matched your search

View File
Whitespace-only changes.
+171
View File
@@ -0,0 +1,171 @@
# -*- coding: utf-8 -*-
"""P2V 산출물 Azure Blob 아카이빙.
P2V 서버는 콜백이 없으므로, 폴링 핸들러가 'done' 을 처음 관측했을 때
FastAPI BackgroundTasks 로 이 모듈을 태운다 (짧은 async I/O — 스레드 워커는 과함).
업로더는 castad `AzureBlobUploader` 를 그대로 재사용한다 (ssulbox blob_service 와
같은 이유 — 같은 Azure 계정에 업로더를 두 벌 둘 이유가 없다).
경로: {user_uuid}/{P2V_BLOB_PREFIX}-f1-{id}/video/... — castad·썰박스와 분리된다.
중복 실행 방지: try_claim_archiving 낙관적 잠금이 첫 태스크에게만 착수권을 준다.
실패 복구: 예외 시 status 를 'done'(archived_at NULL)으로 되돌린다 — 다음 폴링이
다시 선점해 재시도한다. 크래시로 'archiving' 에 갇힌 행은 기동 시 스윕이 되돌린다.
"""
from app.database.session import BackgroundSessionLocal
from app.p2v.constants import STATUS_DONE
from app.p2v.models import P2vF1Job, P2vF2Job
from app.p2v.services import client, f1_service, f2_service
from app.utils.logger import get_logger
from app.utils.upload_blob_as_request import AzureBlobUploader
from config import azure_blob_settings, p2v_settings
logger = get_logger("p2v")
#: 설정되지 않았을 때의 플레이스홀더 (ssulbox blob_service 와 동일 판정)
_PLACEHOLDER_SAS = {"", "your-sas-token", "none"}
def blob_enabled() -> bool:
"""Blob 업로드가 가능한 상태인지. 비활성이면 URL 없이 done 처리된다(개발 환경)."""
token = (azure_blob_settings.AZURE_BLOB_SAS_TOKEN or "").strip()
return token.lower() not in _PLACEHOLDER_SAS
def _uploader(user_uuid: str, kind: str, row_id: int) -> AzureBlobUploader:
return AzureBlobUploader(
user_uuid=user_uuid,
task_id=f"{p2v_settings.P2V_BLOB_PREFIX}-{kind}-{row_id}",
)
async def upload_source_image(
kind: str, row_id: int, user_uuid: str, content: bytes, filename: str
) -> None:
"""원본 업로드 포스터를 Blob 에 보관한다 (잡 생성 직후 백그라운드).
생성 요청이 이미 파일 바이트를 들고 있으므로, 나중에 P2V 에서 되받아오는
대신 이 시점에 바로 올린다. 실패해도 잡 진행에는 영향을 주지 않는다(로그만).
"""
if not blob_enabled():
return
try:
uploader = _uploader(user_uuid, kind, row_id)
ok = await uploader.upload_image_bytes(content, filename or "source.png")
if not ok:
logger.warning(f"[archive] 원본 업로드 실패 {kind} id={row_id}")
return
url = uploader.public_url
model = P2vF1Job if kind == "f1" else P2vF2Job
async with BackgroundSessionLocal() as session:
row = await session.get(model, row_id)
if row is not None:
row.source_image_url = url
await session.commit()
except Exception as e:
# 원본 보관은 부수 기능 — 실패가 잡을 죽이면 안 된다
logger.warning(f"[archive] 원본 업로드 예외 {kind} id={row_id}: {e}")
async def _revert_claim(kind: str, row_id: int) -> None:
"""아카이빙 실패 → 재시도 가능 상태('done', archived_at NULL)로 복구."""
model = P2vF1Job if kind == "f1" else P2vF2Job
try:
async with BackgroundSessionLocal() as session:
row = await session.get(model, row_id)
if row is not None and row.archived_at is None:
row.status = STATUS_DONE
await session.commit()
except Exception as e:
logger.error(f"[archive] 복구 실패 {kind} id={row_id}: {e} — 기동 스윕이 처리한다")
async def archive_f1(row_id: int) -> None:
"""F1 완성 영상·썸네일을 Blob 으로 옮기고 done 전이한다."""
async with BackgroundSessionLocal() as session:
if not await f1_service.try_claim_archiving(session, row_id):
return # 다른 폴링이 이미 집어갔다
await session.commit()
try:
async with BackgroundSessionLocal() as session:
row = await session.get(P2vF1Job, row_id)
if row is None or not row.p2v_job_id:
return
video_url = None
thumb_url = None
if blob_enabled():
p2v_job = await client.request_json(
"GET", f"/api/f1/jobs/{row.p2v_job_id}"
)
artifacts = p2v_job.get("artifacts") or {}
uploader = _uploader(row.user_uuid, "f1", row_id)
if artifacts.get("video"):
content, _ = await client.download(artifacts["video"])
if await uploader.upload_video_bytes(content, "video.mp4"):
video_url = uploader.public_url
else:
raise RuntimeError("영상 Blob 업로드 실패")
if artifacts.get("thumbnail"):
content, _ = await client.download(artifacts["thumbnail"])
if await uploader.upload_image_bytes(content, "thumbnail.jpg"):
thumb_url = uploader.public_url
else:
# 조용히 넘기면 poster_url(og:image)이 영구 결손된다 —
# 영상과 같이 실패시켜 다음 폴링이 아카이빙을 재시도하게 한다
raise RuntimeError("썸네일 Blob 업로드 실패")
# 확정 메타데이터도 이 시점에 마지막으로 미러링해 둔다
f1_service.sync_from_p2v(row, p2v_job)
else:
logger.warning(
f"[archive] Blob 비활성 — f1 id={row_id} URL 없이 done 처리 (개발 환경)"
)
await f1_service.finish_archive(
session, row, video_url=video_url, thumbnail_url=thumb_url
)
await session.commit()
except Exception as e:
logger.error(f"[archive] f1 id={row_id} 아카이빙 실패: {type(e).__name__}: {e}")
await _revert_claim("f1", row_id)
async def archive_f2(row_id: int) -> None:
"""F2 결과 이미지를 Blob 으로 옮기고 done 전이한다."""
async with BackgroundSessionLocal() as session:
if not await f2_service.try_claim_archiving(session, row_id):
return
await session.commit()
try:
async with BackgroundSessionLocal() as session:
row = await session.get(P2vF2Job, row_id)
if row is None or not row.p2v_job_id:
return
image_url = None
if blob_enabled():
p2v_job = await client.request_json(
"GET", f"/api/f2/jobs/{row.p2v_job_id}"
)
artifacts = p2v_job.get("artifacts") or {}
if artifacts.get("image"):
content, _ = await client.download(artifacts["image"])
uploader = _uploader(row.user_uuid, "f2", row_id)
if await uploader.upload_image_bytes(content, "result.png"):
image_url = uploader.public_url
else:
raise RuntimeError("결과 이미지 Blob 업로드 실패")
else:
logger.warning(
f"[archive] Blob 비활성 — f2 id={row_id} URL 없이 done 처리 (개발 환경)"
)
await f2_service.finish_archive(session, row, image_url=image_url)
await session.commit()
except Exception as e:
logger.error(f"[archive] f2 id={row_id} 아카이빙 실패: {type(e).__name__}: {e}")
await _revert_claim("f2", row_id)
+118
View File
@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
"""P2V 서버 HTTP 클라이언트.
httpx.AsyncClient 를 모듈 싱글턴으로 유지한다 (creatomate.py 의 _shared_client 패턴).
모든 요청에 X-P2V-Key 를 실어 보내고, 연결 실패·업스트림 오류를 도메인 예외로 바꾼다.
"""
from typing import Any, Optional
import httpx
from app.p2v.exceptions import P2vUnavailableError, P2vUpstreamError
from app.utils.logger import get_logger
from config import p2v_settings
logger = get_logger("p2v")
#: 기본 타임아웃. 잡 생성(파일 업로드)·레퍼런스 분석(동기 10초 안팎)을 견디도록
#: read 를 넉넉히 잡는다. 폴링 GET 은 서버가 즉시 답하므로 문제되지 않는다.
_DEFAULT_TIMEOUT = httpx.Timeout(10.0, read=120.0)
#: 결과물 다운로드용 (영상 수십 MB)
_DOWNLOAD_TIMEOUT = httpx.Timeout(10.0, read=300.0)
_client: Optional[httpx.AsyncClient] = None
def _headers() -> dict[str, str]:
key = (p2v_settings.P2V_ACCESS_KEY or "").strip()
return {"X-P2V-Key": key} if key else {}
def get_client() -> httpx.AsyncClient:
"""싱글턴 AsyncClient. 커넥션 풀을 프로세스에서 공유한다."""
global _client
if _client is None or _client.is_closed:
_client = httpx.AsyncClient(
base_url=p2v_settings.P2V_BASE_URL.rstrip("/"),
headers=_headers(),
timeout=_DEFAULT_TIMEOUT,
limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
)
return _client
async def close_client() -> None:
"""앱 종료 시 커넥션 풀 정리 (lifespan shutdown 에서 호출)"""
global _client
if _client is not None and not _client.is_closed:
await _client.aclose()
_client = None
def _raise_for_status(resp: httpx.Response) -> None:
"""업스트림 4xx/5xx 를 도메인 예외로 변환한다.
- 401: castad 의 접근 키 문제다. 프론트에 401 을 흘리면 "castad 로그인 만료"로
오독되므로 503 으로 바꾼다.
- 그 외: P2V 의 detail 과 상태 코드를 그대로 중계한다 (조용한 fallback 금지).
"""
if resp.status_code < 400:
return
if resp.status_code == 401:
logger.error("[p2v] 접근 키 거부 — P2V_ACCESS_KEY 설정을 확인할 것")
raise P2vUnavailableError("접근 키가 유효하지 않습니다")
try:
detail = resp.json().get("detail", "")
except Exception:
detail = resp.text[:300]
raise P2vUpstreamError(str(detail) or f"P2V 오류 {resp.status_code}", resp.status_code)
async def request_json(
method: str,
path: str,
*,
data: Optional[dict] = None,
files: Optional[dict] = None,
json_body: Optional[dict] = None,
) -> Any:
"""P2V API 호출 → JSON 응답.
Args:
method: HTTP 메서드
path: /api/... 경로
data: form 필드 (multipart 일 때 files 와 함께)
files: httpx files 딕셔너리 {"poster": (name, bytes, content_type)}
json_body: JSON 바디
Raises:
P2vUnavailableError: 연결 실패·타임아웃·접근 키 거부
P2vUpstreamError: P2V 가 4xx/5xx 를 반환
"""
try:
resp = await get_client().request(
method, path, data=data, files=files, json=json_body
)
except httpx.HTTPError as e:
logger.warning(f"[p2v] {method} {path} 연결 실패: {type(e).__name__}: {e}")
raise P2vUnavailableError(type(e).__name__)
_raise_for_status(resp)
if not resp.content:
return None
return resp.json()
async def download(path: str) -> tuple[bytes, str]:
"""P2V 정적 파일(/files/...)을 받아온다.
Returns:
(바이트, Content-Type)
"""
try:
resp = await get_client().get(path, timeout=_DOWNLOAD_TIMEOUT)
except httpx.HTTPError as e:
logger.warning(f"[p2v] GET {path} 다운로드 실패: {type(e).__name__}: {e}")
raise P2vUnavailableError(type(e).__name__)
_raise_for_status(resp)
return resp.content, resp.headers.get("content-type", "application/octet-stream")
+218
View File
@@ -0,0 +1,218 @@
# -*- coding: utf-8 -*-
"""F1(무빙 포스터) 잡 라이프사이클 + 크레딧.
모든 함수는 **자체 commit 하지 않는다.** 트랜잭션 소유는 라우터/백그라운드 태스크다.
환불 정책 (F2 와 다르다):
F1 실패는 대부분 재시도 가능하다(제목 게이트, 모델 큐 등 — 프론트에 재시도
버튼이 있다). 실패 관측 즉시 환불하면 크레딧 원장의 (job_type, job_ref, type)
유니크 제약 때문에 재시도 시 재차감이 불가능해져 "환불받고 공짜 재시도"가 된다.
그래서 실패 시에는 환불하지 않고, **잡을 버릴 때(삭제)와 고아 스윕에서만** 환불한다.
"""
from datetime import datetime
from typing import Optional
from sqlalchemy import func, select, text, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.credit.services.credit_service import (
deduct_credit_for_job,
refund_credit_for_job,
)
from app.p2v.constants import (
JOB_TYPE_P2V_F1,
ORPHAN_STATUSES,
STATUS_ARCHIVING,
STATUS_DONE,
STATUS_FAILED,
)
from app.p2v.exceptions import P2vJobNotFoundError
from app.p2v.models import P2vF1Job
from app.utils.logger import get_logger
from config import p2v_settings
logger = get_logger("p2v")
async def create_job(
session: AsyncSession, *, user_uuid: str, name: str
) -> P2vF1Job:
"""잡 행 생성 + 크레딧 선차감 (한 트랜잭션 — 호출부가 commit).
행을 먼저 flush 해 id 를 확보한 뒤 그 id 를 멱등 키(job_ref)로 차감한다.
크레딧이 부족하면 InsufficientCreditError 가 올라가고 행도 롤백된다 —
P2V 는 아직 호출되지 않았으므로 실비용(OpenAI 등)이 나가지 않는다.
Raises:
InsufficientCreditError: 잔액 부족 (전역 핸들러가 402 로 변환)
"""
row = P2vF1Job(
user_uuid=user_uuid,
name=name or None,
status="queued",
credit_amount=p2v_settings.P2V_CREDITS_PER_F1,
)
session.add(row)
await session.flush() # id 확보
await deduct_credit_for_job(
session=session,
user_uuid=user_uuid,
amount=p2v_settings.P2V_CREDITS_PER_F1,
job_type=JOB_TYPE_P2V_F1,
job_ref=str(row.id),
reason="무빙 포스터 생성",
)
logger.info(f"[f1] 잡 생성 id={row.id} user={user_uuid}")
return row
async def get_owned(
session: AsyncSession, job_id: int, user_uuid: str
) -> P2vF1Job:
"""소유권 검사 포함 조회. 남의 잡이면 존재를 알리지 않고 동일하게 404."""
row = await session.get(P2vF1Job, job_id)
if row is None or row.user_uuid != user_uuid:
raise P2vJobNotFoundError()
return row
async def refund_job(
session: AsyncSession, row: P2vF1Job, reason: str
) -> None:
"""선차감분 환불 (멱등 — 이미 환불했거나 차감 기록이 없으면 조용히 넘어간다)."""
await refund_credit_for_job(
session=session,
user_uuid=row.user_uuid,
amount=row.credit_amount,
job_type=JOB_TYPE_P2V_F1,
job_ref=str(row.id),
reason=reason,
)
async def fail_job(
session: AsyncSession, row: P2vF1Job, detail: str, *, refund: bool
) -> None:
"""실패 처리.
Args:
refund: True 면 환불까지. P2V 호출 자체가 실패했거나(실비용 없음)
잡이 P2V 에서 사라져 재시도가 불가능할 때만 True 로 준다.
일반 스테이지 실패는 재시도 가능하므로 False (모듈 docstring 참조).
"""
row.status = STATUS_FAILED
row.error = detail[:1000]
if refund:
await refund_job(session, row, reason=f"무빙 포스터 실패: {detail[:100]}")
logger.info(f"[f1] 실패 처리 id={row.id} refund={refund} detail={detail[:200]}")
def sync_from_p2v(row: P2vF1Job, p2v_job: dict) -> None:
"""P2V 잡 JSON → castad 행 미러링 (순수 상태 복사 — DB 호출 없음).
'done' 은 여기서 반영하지 않는다 — Blob 아카이빙이 끝나야 done 이다
(archive_service 가 archiving → done 전이를 소유한다).
실패도 상태만 미러하고 환불하지 않는다 (재시도 가능 — 모듈 docstring 참조).
"""
p2v_status = p2v_job.get("status", "")
if p2v_status in ("queued", "running", "awaiting_review"):
row.status = p2v_status
elif p2v_status == "failed":
row.status = STATUS_FAILED
err = p2v_job.get("error") or {}
row.error = f"{err.get('stage', '?')}: {err.get('detail', '')}"[:1000]
if p2v_job.get("name"):
row.name = str(p2v_job["name"])[:100]
if p2v_job.get("narration") is not None:
row.narration = p2v_job["narration"]
md = p2v_job.get("metadata")
if md:
row.event_name = (md.get("event_name") or "")[:200] or None
row.date_text = (md.get("date_text") or "")[:100] or None
row.place = (md.get("place") or "")[:200] or None
row.keywords = md.get("keywords")
if p2v_job.get("duration") is not None:
row.duration = p2v_job["duration"]
async def try_claim_archiving(session: AsyncSession, job_id: int) -> bool:
"""Blob 아카이빙 착수권 선점 (낙관적 잠금).
폴링이 겹쳐도 UPDATE 는 한 요청만 성공한다. rowcount 0 이면 다른 폴링이
이미 집어갔거나 이미 아카이브된 것이므로 조용히 물러난다.
"""
result = await session.execute(
update(P2vF1Job)
.where(
P2vF1Job.id == job_id,
P2vF1Job.status != STATUS_ARCHIVING,
P2vF1Job.archived_at.is_(None),
)
.values(status=STATUS_ARCHIVING)
.execution_options(synchronize_session=False)
)
return result.rowcount > 0
async def finish_archive(
session: AsyncSession,
row: P2vF1Job,
*,
video_url: Optional[str],
thumbnail_url: Optional[str],
) -> None:
"""아카이빙 완료 — Blob URL 기록 + done 전이."""
row.p2v_video_url = video_url
row.poster_url = thumbnail_url
row.archived_at = datetime.now()
row.status = STATUS_DONE
logger.info(f"[f1] 아카이브 완료 id={row.id} video={bool(video_url)}")
async def sweep_orphans(session: AsyncSession) -> int:
"""방치된 잡 정리 (앱 기동 시 lifespan 훅에서 호출).
1) 진행/검수 상태로 P2V_ORPHAN_TIMEOUT_HOURS 를 넘긴 잡 → 환불 + 실패
(검수 화면에서 이탈한 사용자의 선차감분이 증발하는 것을 막는다 — 설계 R-1)
2) archiving 으로 P2V_ARCHIVE_STALE_MINUTES 넘게 방치된 잡 → 'done'(archived_at
NULL) 으로 되돌린다. 다음 폴링이 아카이빙을 다시 선점한다 (설계 R-3 크래시 복구)
시각 비교는 DB 시계(func.now())로 한다 — 앱과 DB 의 타임존이 다를 수 있다.
"""
swept = 0
orphan_cutoff = func.date_sub(
func.now(), text(f"INTERVAL {int(p2v_settings.P2V_ORPHAN_TIMEOUT_HOURS)} HOUR")
)
result = await session.execute(
select(P2vF1Job).where(
P2vF1Job.status.in_(ORPHAN_STATUSES),
P2vF1Job.created_at < orphan_cutoff,
)
)
for row in result.scalars().all():
await fail_job(
session, row, "시간 초과 — 크레딧을 자동 환불했습니다", refund=True
)
swept += 1
stale_cutoff = func.date_sub(
func.now(),
text(f"INTERVAL {int(p2v_settings.P2V_ARCHIVE_STALE_MINUTES)} MINUTE"),
)
result = await session.execute(
update(P2vF1Job)
.where(
P2vF1Job.status == STATUS_ARCHIVING,
P2vF1Job.updated_at < stale_cutoff,
)
.values(status=STATUS_DONE)
.execution_options(synchronize_session=False)
)
if result.rowcount:
logger.info(f"[f1] 정체된 archiving {result.rowcount}건 재시도 가능으로 복구")
return swept
+190
View File
@@ -0,0 +1,190 @@
# -*- coding: utf-8 -*-
"""F2(포스터 스타일링) 잡 라이프사이클 + 크레딧.
모든 함수는 **자체 commit 하지 않는다.** 트랜잭션 소유는 라우터/백그라운드 태스크다.
F1 과 달리 F2 에는 재시도 경로가 없다(P2V API 에 retry 엔드포인트 자체가 없음).
따라서 실패를 관측하는 즉시 환불한다.
"""
from datetime import datetime
from typing import Optional
from sqlalchemy import func, select, text, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.credit.services.credit_service import (
deduct_credit_for_job,
refund_credit_for_job,
)
from app.p2v.constants import (
JOB_TYPE_P2V_F2,
STATUS_ARCHIVING,
STATUS_DONE,
STATUS_FAILED,
)
from app.p2v.exceptions import P2vJobNotFoundError
from app.p2v.models import P2vF2Job
from app.utils.logger import get_logger
from config import p2v_settings
logger = get_logger("p2v")
async def create_job(
session: AsyncSession,
*,
user_uuid: str,
name: Optional[str],
template_id: str,
template_name: Optional[str],
license: Optional[str],
format: str,
) -> P2vF2Job:
"""잡 행 생성 + 크레딧 선차감 (한 트랜잭션 — 호출부가 commit).
템플릿 이름·라이선스는 이 시점의 스냅샷이다 — 템플릿이 나중에 삭제되거나
등급이 바뀌어도 "이 결과물이 어떤 등급 레퍼런스로 만들어졌는지"가 남는다.
Raises:
InsufficientCreditError: 잔액 부족 (전역 핸들러가 402 로 변환)
"""
row = P2vF2Job(
user_uuid=user_uuid,
name=(name or "")[:100] or None,
template_id=template_id,
template_name=(template_name or "")[:100] or None,
license=(license or "")[:20] or None,
format=format,
status="queued",
credit_amount=p2v_settings.P2V_CREDITS_PER_F2,
)
session.add(row)
await session.flush() # id 확보
await deduct_credit_for_job(
session=session,
user_uuid=user_uuid,
amount=p2v_settings.P2V_CREDITS_PER_F2,
job_type=JOB_TYPE_P2V_F2,
job_ref=str(row.id),
reason="포스터 스타일링",
)
logger.info(f"[f2] 잡 생성 id={row.id} user={user_uuid} template={template_id}")
return row
async def get_owned(
session: AsyncSession, job_id: int, user_uuid: str
) -> P2vF2Job:
"""소유권 검사 포함 조회. 남의 잡이면 존재를 알리지 않고 동일하게 404."""
row = await session.get(P2vF2Job, job_id)
if row is None or row.user_uuid != user_uuid:
raise P2vJobNotFoundError()
return row
async def refund_job(session: AsyncSession, row: P2vF2Job, reason: str) -> None:
"""선차감분 환불 (멱등 — 이미 환불했거나 차감 기록이 없으면 조용히 넘어간다)."""
await refund_credit_for_job(
session=session,
user_uuid=row.user_uuid,
amount=row.credit_amount,
job_type=JOB_TYPE_P2V_F2,
job_ref=str(row.id),
reason=reason,
)
async def fail_job(session: AsyncSession, row: P2vF2Job, detail: str) -> None:
"""실패 처리 + 즉시 환불 (F2 는 재시도 경로가 없다)."""
row.status = STATUS_FAILED
row.error = detail[:1000]
await refund_credit_for_job(
session=session,
user_uuid=row.user_uuid,
amount=row.credit_amount,
job_type=JOB_TYPE_P2V_F2,
job_ref=str(row.id),
reason=f"포스터 스타일링 실패: {detail[:100]}",
)
logger.info(f"[f2] 실패 처리(환불) id={row.id} detail={detail[:200]}")
async def sync_from_p2v(
session: AsyncSession, row: P2vF2Job, p2v_job: dict
) -> None:
"""P2V 잡 JSON → castad 행 미러링.
'done' 은 반영하지 않는다 — Blob 아카이빙 완료가 done 이다.
'failed' 는 즉시 환불한다 (F1 과 다른 지점).
"""
p2v_status = p2v_job.get("status", "")
if p2v_status in ("queued", "running"):
row.status = p2v_status
elif p2v_status == "failed" and row.status != STATUS_FAILED:
err = p2v_job.get("error") or {}
await fail_job(
session, row, f"{err.get('stage', '?')}: {err.get('detail', '')}"
)
async def try_claim_archiving(session: AsyncSession, job_id: int) -> bool:
"""Blob 아카이빙 착수권 선점 (낙관적 잠금 — f1_service 와 동일 방식)."""
result = await session.execute(
update(P2vF2Job)
.where(
P2vF2Job.id == job_id,
P2vF2Job.status != STATUS_ARCHIVING,
P2vF2Job.archived_at.is_(None),
)
.values(status=STATUS_ARCHIVING)
.execution_options(synchronize_session=False)
)
return result.rowcount > 0
async def finish_archive(
session: AsyncSession, row: P2vF2Job, *, image_url: Optional[str]
) -> None:
"""아카이빙 완료 — Blob URL 기록 + done 전이."""
row.p2v_poster_url = image_url
row.archived_at = datetime.now()
row.status = STATUS_DONE
logger.info(f"[f2] 아카이브 완료 id={row.id} image={bool(image_url)}")
async def sweep_orphans(session: AsyncSession) -> int:
"""방치된 잡 정리 — f1_service.sweep_orphans 와 같은 규칙 (검수 단계만 없다)."""
swept = 0
orphan_cutoff = func.date_sub(
func.now(), text(f"INTERVAL {int(p2v_settings.P2V_ORPHAN_TIMEOUT_HOURS)} HOUR")
)
result = await session.execute(
select(P2vF2Job).where(
P2vF2Job.status.in_(("queued", "running")),
P2vF2Job.created_at < orphan_cutoff,
)
)
for row in result.scalars().all():
await fail_job(session, row, "시간 초과 — 크레딧을 자동 환불했습니다")
swept += 1
stale_cutoff = func.date_sub(
func.now(),
text(f"INTERVAL {int(p2v_settings.P2V_ARCHIVE_STALE_MINUTES)} MINUTE"),
)
result = await session.execute(
update(P2vF2Job)
.where(
P2vF2Job.status == STATUS_ARCHIVING,
P2vF2Job.updated_at < stale_cutoff,
)
.values(status=STATUS_DONE)
.execution_options(synchronize_session=False)
)
if result.rowcount:
logger.info(f"[f2] 정체된 archiving {result.rowcount}건 재시도 가능으로 복구")
return swept