feat(ssulbox): 썰박스 생성 파이프라인 통합 및 콘텐츠 목록 UNION
This commit is contained in:
1 parent
8096837b13
commit
666c3bf6d1
77 files changed
+15912
-349
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,66 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""썰박스 산출물 Blob 업로드.
|
||||
|
||||
castad `AzureBlobUploader` 를 그대로 재사용한다 — 원본 썰박스의 `blob_client.py`
|
||||
는 이식하지 않는다. 같은 Azure 계정을 쓰므로 업로더를 두 벌 둘 이유가 없다.
|
||||
|
||||
경로는 `{user_uuid}/{task_id}/video/{file}` 형태가 되는데, ADO2 콘텐츠와 섞이지 않도록
|
||||
task_id 자리에 `ssulbox-{id}` 접두를 붙인다.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
from config import azure_blob_settings, ssulbox_settings
|
||||
|
||||
logger = get_logger("ssulbox")
|
||||
|
||||
#: 설정되지 않았을 때의 플레이스홀더 (config.py 기본값)
|
||||
_PLACEHOLDER_SAS = {"", "your-sas-token", "none"}
|
||||
|
||||
|
||||
def blob_enabled() -> bool:
|
||||
"""Blob 업로드가 가능한 상태인지.
|
||||
|
||||
비활성이면 로컬 파일을 그대로 서빙한다(개발 환경).
|
||||
"""
|
||||
token = (azure_blob_settings.AZURE_BLOB_SAS_TOKEN or "").strip()
|
||||
return token.lower() not in _PLACEHOLDER_SAS
|
||||
|
||||
|
||||
async def upload_ssul_video(
|
||||
mp4_path: Path, user_uuid: Optional[str], content_id: int
|
||||
) -> Optional[str]:
|
||||
"""완성 영상을 Blob 에 올리고 공개 URL 을 반환. 실패·비활성이면 None.
|
||||
|
||||
Args:
|
||||
mp4_path: 로컬 mp4 경로
|
||||
user_uuid: 소유자. 탈퇴로 NULL 이면 업로드하지 않는다
|
||||
content_id: `ssul_content.id`
|
||||
|
||||
Returns:
|
||||
SAS 토큰이 제외된 공개 URL, 또는 None
|
||||
"""
|
||||
if not blob_enabled():
|
||||
logger.info("[upload_ssul_video] Blob 비활성 — 로컬 서빙")
|
||||
return None
|
||||
if not user_uuid:
|
||||
logger.warning(f"[upload_ssul_video] user_uuid 없음 id={content_id}")
|
||||
return None
|
||||
if not mp4_path.exists():
|
||||
logger.error(f"[upload_ssul_video] 파일 없음 {mp4_path}")
|
||||
return None
|
||||
|
||||
# ADO2 영상과 경로를 분리한다
|
||||
task_id = f"{ssulbox_settings.SSULBOX_BLOB_PREFIX}-{content_id}"
|
||||
uploader = AzureBlobUploader(user_uuid=user_uuid, task_id=task_id)
|
||||
|
||||
success = await uploader.upload_video(file_path=str(mp4_path))
|
||||
if not success:
|
||||
logger.error(f"[upload_ssul_video] 업로드 실패 id={content_id}")
|
||||
return None
|
||||
|
||||
logger.info(f"[upload_ssul_video] OK id={content_id} url={uploader.public_url}")
|
||||
return uploader.public_url
|
||||
@@ -0,0 +1,327 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""네이버 지도 업장 검색 (키 불필요, Playwright).
|
||||
|
||||
`map.naver.com/p/search/{query}` 의 검색 리스트 iframe(`pcmap.place.naver.com/place/list`)
|
||||
안에 있는 `__APOLLO_STATE__` 를 파싱해, 동명 업장들을 주소로 구분한 후보 목록을 만든다.
|
||||
각 후보는 `place_url`(map.naver.com/p/entry/place/{id})을 가지므로, 사용자가 하나를 고르면
|
||||
그 URL 을 그대로 생성 파이프라인(generator/naver.py)에 넘겨 정확히 그 가게를 크롤링한다.
|
||||
|
||||
**castad `/search/accommodation` 으로 대체할 수 없다.** 그쪽은 네이버 *검색 API* 라
|
||||
`title`/`address`/`roadAddress` 만 주고 `place_url` 이 없는데, generator 가 place 페이지를
|
||||
크롤링하므로 URL 이 반드시 필요하다. (castad `NvMapPwScraper` 는 후보=NAVER API,
|
||||
place_id 해석=Playwright 로 2단계를 밟지만 여기서는 지도만으로 한 번에 얻는다.)
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from urllib.parse import quote
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
# URL 정규화(단축링크 해석·place_id 추출)는 castad 크롤러 것을 그대로 쓴다.
|
||||
# 무거운 scrap() 은 쓰지 않는다 — fetch_place_detail docstring 참조.
|
||||
from app.utils.nvMapScraper import NvMapScraper, URLNotFoundException
|
||||
|
||||
logger = get_logger("ssulbox")
|
||||
|
||||
DESKTOP_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
def _extract_apollo_state(html: str) -> dict | None:
|
||||
"""HTML 안의 `__APOLLO_STATE__ = { ... };` 객체를 중괄호 균형으로 안전하게 추출."""
|
||||
i = html.find("__APOLLO_STATE__")
|
||||
if i < 0:
|
||||
return None
|
||||
j = html.find("{", i)
|
||||
if j < 0:
|
||||
return None
|
||||
depth = 0
|
||||
in_str = False
|
||||
esc = False
|
||||
for k in range(j, len(html)):
|
||||
c = html[k]
|
||||
if in_str:
|
||||
if esc:
|
||||
esc = False
|
||||
elif c == "\\":
|
||||
esc = True
|
||||
elif c == '"':
|
||||
in_str = False
|
||||
else:
|
||||
if c == '"':
|
||||
in_str = True
|
||||
elif c == "{":
|
||||
depth += 1
|
||||
elif c == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
try:
|
||||
return json.loads(html[j : k + 1])
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _candidates_from_state(state: dict, limit: int) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
for key, obj in state.items():
|
||||
if not key.startswith("PlaceListBusinessesItem:"):
|
||||
continue
|
||||
if not isinstance(obj, dict):
|
||||
continue
|
||||
name = obj.get("name")
|
||||
pid = obj.get("id")
|
||||
if not (name and pid and str(pid).isdigit()):
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"title": name,
|
||||
"category": obj.get("category") or "",
|
||||
# 표시용 주소는 '서울 성동구 금호동3가' 같은 commonAddress 를 우선(동명 구분에 최적)
|
||||
"address": obj.get("commonAddress") or obj.get("fullAddress") or "",
|
||||
"roadAddress": obj.get("fullAddress") or obj.get("roadAddress") or "",
|
||||
"place_url": f"https://map.naver.com/p/entry/place/{pid}",
|
||||
}
|
||||
)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
async def _search(query: str, limit: int) -> list[dict]:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],
|
||||
)
|
||||
try:
|
||||
ctx = await browser.new_context(
|
||||
user_agent=DESKTOP_UA, locale="ko-KR", timezone_id="Asia/Seoul",
|
||||
viewport={"width": 1280, "height": 800},
|
||||
extra_http_headers={"Accept-Language": "ko-KR,ko;q=0.9"},
|
||||
)
|
||||
page = await ctx.new_page()
|
||||
await page.goto(
|
||||
f"https://map.naver.com/p/search/{quote(query)}",
|
||||
wait_until="domcontentloaded", timeout=40000,
|
||||
)
|
||||
# 검색 리스트 iframe 이 뜰 때까지 대기(최대 ~12초)
|
||||
frame = None
|
||||
for _ in range(24):
|
||||
for f in page.frames:
|
||||
if "pcmap.place.naver.com/place/list" in f.url:
|
||||
frame = f
|
||||
break
|
||||
if frame:
|
||||
break
|
||||
# 단일 결과면 곧바로 place 상세로 리다이렉트됨 → 후보 1개로 처리.
|
||||
# 이때도 **주소를 반드시 채운다**. 예전에는 빈 문자열을 돌려줬는데,
|
||||
# 그러면 프론트가 주소를 못 보내고 지역(region)이 NULL 이 되어
|
||||
# 그 콘텐츠가 통합 목록의 지역 필터에서 영구 제외된다.
|
||||
if "/place/" in page.url and "/search/" not in page.url:
|
||||
detail = await _extract_detail_from_page(page)
|
||||
if detail:
|
||||
detail["place_url"] = page.url
|
||||
return [detail]
|
||||
# 상세 파싱까지 실패하면 최소 정보라도 준다(생성은 가능해야 한다)
|
||||
return [{"title": query, "category": "", "address": "",
|
||||
"roadAddress": "", "place_url": page.url}]
|
||||
await page.wait_for_timeout(500)
|
||||
if not frame:
|
||||
return []
|
||||
# apollo state 가 채워질 시간을 조금 더 준다
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
for _ in range(6):
|
||||
if state and any(k.startswith("PlaceListBusinessesItem:") for k in state):
|
||||
break
|
||||
await page.wait_for_timeout(600)
|
||||
html = await frame.content()
|
||||
state = _extract_apollo_state(html)
|
||||
if not state:
|
||||
return []
|
||||
return _candidates_from_state(state, limit)
|
||||
finally:
|
||||
await browser.close()
|
||||
|
||||
|
||||
def _detail_from_state(state: dict) -> dict | None:
|
||||
"""place 상세 페이지 apollo state → {title, category, address, roadAddress}.
|
||||
|
||||
실측(2026-07-29, `zzz/_probe_place_detail.py`): 상세는 `pcmap.place.naver.com`
|
||||
iframe 안에 `PlaceDetailBase:{place_id}` 키로 들어 있고 name/address/roadAddress/
|
||||
category 를 모두 갖는다. iframe 경로에 업종 세그먼트가 끼므로
|
||||
(`/restaurant/{id}/home`) 경로를 고정하면 안 된다.
|
||||
"""
|
||||
for key, obj in state.items():
|
||||
if not key.startswith("PlaceDetailBase:") or not isinstance(obj, dict):
|
||||
continue
|
||||
name = (obj.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
return {
|
||||
"title": name,
|
||||
"category": (obj.get("category") or "").strip(),
|
||||
"address": (obj.get("address") or "").strip(),
|
||||
"roadAddress": (obj.get("roadAddress") or "").strip(),
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
async def _extract_detail_from_page(page, tries: int = 12) -> dict | None:
|
||||
"""열려 있는 place 상세 페이지에서 업장 정보를 뽑는다(iframe 탐색 + 재시도)."""
|
||||
for _ in range(tries):
|
||||
for frame in [page, *[f for f in page.frames if "pcmap" in f.url]]:
|
||||
try:
|
||||
html = await frame.content()
|
||||
except Exception:
|
||||
continue
|
||||
state = _extract_apollo_state(html)
|
||||
if not state:
|
||||
continue
|
||||
detail = _detail_from_state(state)
|
||||
if detail:
|
||||
return detail
|
||||
await page.wait_for_timeout(700)
|
||||
return None
|
||||
|
||||
|
||||
async def _detail(place_url: str) -> dict | None:
|
||||
"""place URL 하나를 열어 업장명·주소를 수집."""
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--disable-blink-features=AutomationControlled", "--no-sandbox"],
|
||||
)
|
||||
try:
|
||||
ctx = await browser.new_context(
|
||||
user_agent=DESKTOP_UA, locale="ko-KR", timezone_id="Asia/Seoul",
|
||||
viewport={"width": 1280, "height": 800},
|
||||
extra_http_headers={"Accept-Language": "ko-KR,ko;q=0.9"},
|
||||
)
|
||||
page = await ctx.new_page()
|
||||
await page.goto(place_url, wait_until="domcontentloaded", timeout=40000)
|
||||
detail = await _extract_detail_from_page(page)
|
||||
if detail:
|
||||
detail["place_url"] = page.url
|
||||
return detail
|
||||
finally:
|
||||
await browser.close()
|
||||
|
||||
|
||||
def _detail_blocking(place_url: str) -> dict | None:
|
||||
"""`_search_blocking` 과 같은 이유로 스레드에서 자체 루프를 쓴다."""
|
||||
loop = (
|
||||
asyncio.ProactorEventLoop() if sys.platform == "win32"
|
||||
else asyncio.new_event_loop()
|
||||
)
|
||||
try:
|
||||
return loop.run_until_complete(_detail(place_url))
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
async def fetch_place_detail(
|
||||
place_url: str, timeout: float = 45.0
|
||||
) -> dict | None:
|
||||
"""place URL 로 업장명·주소를 수집. 실패하면 None.
|
||||
|
||||
**업장명과 주소는 항상 함께 수집한다** — 주소가 없으면 지역(region)을 못 만들고,
|
||||
그러면 통합 콘텐츠 목록의 지역 필터에서 그 콘텐츠가 영구히 제외된다.
|
||||
|
||||
URL 정규화는 castad `NvMapScraper.parse_url()` 을 **재사용**한다.
|
||||
`naver.me` 단축링크를 브라우저 없이 HTTP 리다이렉트로 풀고
|
||||
`place.naver.com/{업종}/{id}` 형식도 처리하므로, ADO2 크롤링과 **같은 URL 형식**을
|
||||
받아들이게 된다. 형식이 아예 아니면 브라우저를 띄우기 전에 즉시 포기한다.
|
||||
|
||||
반면 `NvMapScraper.scrap()` 은 쓰지 않는다 — 사진 다중 페이지·리뷰 통계·
|
||||
편의시설·메뉴까지 전부 긁어오므로 이름·주소만 필요한 여기에는 과하다.
|
||||
|
||||
실패해도 예외를 올리지 않는다: 이 정보는 목록 표시·필터용 부가 정보이고,
|
||||
생성 자체는 place_url 만으로 진행되므로 크롤링 실패가 생성을 막아선 안 된다.
|
||||
"""
|
||||
place_url = (place_url or "").strip()
|
||||
if not place_url:
|
||||
return None
|
||||
|
||||
# 단축링크 해석 + place_id 추출 (브라우저 없이). 실패해도 원본 URL 로 계속 간다.
|
||||
try:
|
||||
place_id = await NvMapScraper(place_url).parse_url()
|
||||
place_url = f"https://map.naver.com/p/entry/place/{place_id}"
|
||||
except URLNotFoundException:
|
||||
logger.warning(f"[fetch_place_detail] place URL 아님 - {place_url}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
f"[fetch_place_detail] URL 정규화 실패, 원본으로 진행 - "
|
||||
f"{type(e).__name__}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
detail = await asyncio.wait_for(
|
||||
asyncio.to_thread(_detail_blocking, place_url), timeout=timeout
|
||||
)
|
||||
if detail:
|
||||
logger.info(
|
||||
f"[fetch_place_detail] {place_url} → "
|
||||
f"title={detail['title']!r} road={detail['roadAddress']!r}"
|
||||
)
|
||||
else:
|
||||
logger.warning(f"[fetch_place_detail] 정보 없음 - {place_url}")
|
||||
return detail
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(f"[fetch_place_detail] TIMEOUT ({timeout}s) - {place_url}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[fetch_place_detail] FAILED {place_url} - {type(e).__name__}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _search_blocking(query: str, limit: int) -> list[dict]:
|
||||
"""별도 스레드에서 자체 이벤트 루프로 Playwright 실행.
|
||||
|
||||
Windows 의 웹서버 루프(Selector)는 서브프로세스를 못 띄워 Playwright 가 즉시 실패한다.
|
||||
→ 이 함수는 워커 스레드에서 Proactor 루프(윈도우) 를 새로 만들어 그 위에서 돌린다.
|
||||
"""
|
||||
if sys.platform == "win32":
|
||||
loop = asyncio.ProactorEventLoop()
|
||||
else:
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
return loop.run_until_complete(_search(query, limit))
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
async def search_places(query: str, limit: int = 8, timeout: float = 35.0) -> list[dict]:
|
||||
"""업장명으로 네이버 지도 후보 목록을 반환. 실패/타임아웃이면 빈 리스트.
|
||||
|
||||
실패해도 예외를 올리지 않는다 — 사용자에게는 네이버 링크를 직접 붙여넣는
|
||||
우회 경로가 있으므로 흐름을 막지 않는다. 다만 원본은 예외를 통째로 삼켜
|
||||
디버깅이 불가능했으므로 로그는 남긴다.
|
||||
"""
|
||||
query = (query or "").strip()
|
||||
if len(query) < 2:
|
||||
return []
|
||||
try:
|
||||
results = await asyncio.wait_for(
|
||||
asyncio.to_thread(_search_blocking, query, limit), timeout=timeout
|
||||
)
|
||||
logger.info(f"[search_places] query='{query}' → {len(results)}건")
|
||||
return results
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(f"[search_places] TIMEOUT ({timeout}s) query='{query}'")
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[search_places] FAILED query='{query}' - {type(e).__name__}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
return []
|
||||
@@ -0,0 +1,294 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""썰박스 생성 잡 라이프사이클 — 생성(선차감) · 진행 · 완료 · 실패(환불) · 고아 스윕.
|
||||
|
||||
**모든 함수는 자체 commit 하지 않는다.** caller 가 트랜잭션을 소유하고 마지막에 한 번
|
||||
커밋한다(둘 다 성공 or 둘 다 롤백). 되돌릴 수 없는 부수효과(로컬 파일 삭제)는
|
||||
`finalize_task` 가 반환한 폴더를 caller 가 **커밋 성공 후에** 정리한다.
|
||||
|
||||
원본과 달라진 점: Task/Content 를 한 테이블(`ssul_content`)로 합쳤으므로
|
||||
`finalize` 가 INSERT 가 아니라 **UPDATE** 다 — 멱등성이 자연히 확보된다.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.credit.services.credit_service import (
|
||||
deduct_credit_for_job,
|
||||
refund_credit_for_job,
|
||||
)
|
||||
from app.ssulbox.constants import JOB_TYPE_SSUL, ORPHAN_STATUSES, SsulTaskStatus
|
||||
from app.ssulbox.models import SsulContent
|
||||
# castad 와 **같은 규칙으로** 지역을 뽑는다. 통합 목록에서 한 필터가 양쪽을
|
||||
# 걸러야 하므로 region 값의 형식이 일치해야 한다.
|
||||
from app.utils.address_parser import extract_region_from_address
|
||||
from app.utils.logger import get_logger
|
||||
from config import ssulbox_settings
|
||||
|
||||
logger = get_logger("ssulbox")
|
||||
|
||||
|
||||
def _job_ref(content_id: int) -> str:
|
||||
"""크레딧 원장 멱등 키. (job_type, job_ref, type) 유니크의 일부"""
|
||||
return str(content_id)
|
||||
|
||||
|
||||
async def create_task(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
user_uuid: str,
|
||||
scenario: str,
|
||||
input_text: str,
|
||||
scenes: int,
|
||||
seconds: int,
|
||||
store_name: Optional[str] = None,
|
||||
road_address: Optional[str] = None,
|
||||
address: Optional[str] = None,
|
||||
) -> SsulContent:
|
||||
"""행 삽입 + 크레딧 선차감을 **한 트랜잭션**으로 묶는다.
|
||||
|
||||
사후차감이면 차감 전에 동시 요청이 들어와 크레딧 1개로 여러 개를 만들 수 있다.
|
||||
잔액 부족 시 `InsufficientCreditError` 가 전파되므로 caller 가 402 로 변환한다.
|
||||
|
||||
`store_name`/`address` 는 검색으로 업장을 고른 경우에만 들어온다.
|
||||
**생성 시점에 넣는 이유**: 통합 목록의 store_name/region 필터가 이 값에 걸리고,
|
||||
생성 중인 항목도 `내 콘텐츠`에서 업장명으로 보여야 한다. 완료를 기다리면
|
||||
그 사이 목록에 이름 없는 카드가 뜬다.
|
||||
주소는 region 추출에만 쓰고 저장하지 않는다(castad `project` 와 달리 상세 주소를
|
||||
보관할 화면이 없다). castad `/home/crawl` 과 같이 **도로명·지번을 모두** 넘겨
|
||||
도로명에서 시/군 추출이 실패하면 지번으로 재시도하게 한다.
|
||||
"""
|
||||
row = SsulContent(
|
||||
user_uuid=user_uuid,
|
||||
scenario=scenario,
|
||||
input=input_text,
|
||||
scenes=scenes,
|
||||
seconds=seconds,
|
||||
status=SsulTaskStatus.QUEUED.value,
|
||||
step=0,
|
||||
# store_name 은 NOT NULL 이다. 아직 모르면 빈 문자열 —
|
||||
# 채우는 쪽(`set_place_info`)이 falsy 검사로 "미확정"을 판단한다.
|
||||
store_name=store_name or "",
|
||||
region=extract_region_from_address(road_address or None, address or None)
|
||||
or None,
|
||||
# castad `/home/crawl` 과 동일: 도로명 우선, 없으면 지번
|
||||
detail_region_info=(road_address or address or None),
|
||||
)
|
||||
session.add(row)
|
||||
await session.flush() # autoincrement id 확보 — 크레딧 멱등 키로 쓴다
|
||||
|
||||
await deduct_credit_for_job(
|
||||
session=session,
|
||||
user_uuid=user_uuid,
|
||||
amount=ssulbox_settings.SSULBOX_CREDITS_PER_VIDEO,
|
||||
job_type=JOB_TYPE_SSUL,
|
||||
job_ref=_job_ref(row.id),
|
||||
reason="썰박스 생성",
|
||||
)
|
||||
logger.info(
|
||||
f"[create_task] id={row.id} user={user_uuid} scenario={scenario}"
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def mark_running(session: AsyncSession, content_id: int) -> None:
|
||||
"""잡이 실제로 시작됐을 때"""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None or row.status != SsulTaskStatus.QUEUED.value:
|
||||
return
|
||||
row.status = SsulTaskStatus.RUNNING.value
|
||||
|
||||
|
||||
async def update_step(session: AsyncSession, content_id: int, step: int) -> None:
|
||||
"""진행 단계 갱신.
|
||||
|
||||
원본은 step 을 인메모리에만 뒀지만 castad 는 SSE 대신 폴링을 쓰므로
|
||||
**DB 에 영속**해야 `GET /ssul/tasks/{id}` 가 진행률을 돌려줄 수 있다.
|
||||
"""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None or row.status in (
|
||||
SsulTaskStatus.DONE.value,
|
||||
SsulTaskStatus.ERROR.value,
|
||||
):
|
||||
return
|
||||
row.status = SsulTaskStatus.RUNNING.value
|
||||
row.step = max(row.step, step) # 뒤로 가지 않는다
|
||||
|
||||
|
||||
async def finalize_task(
|
||||
session: AsyncSession,
|
||||
content_id: int,
|
||||
mp4_path: Path,
|
||||
*,
|
||||
store_name: Optional[str] = None,
|
||||
region: Optional[str] = None,
|
||||
) -> tuple[Optional[SsulContent], Optional[Path]]:
|
||||
"""완료 처리. 같은 행을 UPDATE 하므로 **멱등**이다.
|
||||
|
||||
Returns:
|
||||
(행, 커밋 성공 후 정리할 로컬 job 폴더 또는 None)
|
||||
폴더 삭제는 되돌릴 수 없으므로 반드시 커밋이 성공한 뒤에 한다.
|
||||
"""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None:
|
||||
logger.warning(f"[finalize_task] 행 없음 id={content_id}")
|
||||
return None, None
|
||||
if row.status == SsulTaskStatus.DONE.value:
|
||||
return row, None # 이미 처리됨
|
||||
|
||||
job_dir = mp4_path.parent
|
||||
cleanup: Optional[Path] = None
|
||||
video_url: Optional[str] = None
|
||||
|
||||
# Blob 이 설정돼 있으면 업로드하고 로컬은 커밋 후 정리한다.
|
||||
# 아니면 로컬 경로를 그대로 서빙한다.
|
||||
try:
|
||||
from app.ssulbox.services.blob_service import upload_ssul_video
|
||||
|
||||
video_url = await upload_ssul_video(mp4_path, row.user_uuid, content_id)
|
||||
if video_url:
|
||||
cleanup = job_dir
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[finalize_task] Blob 업로드 실패 id={content_id} - {type(e).__name__}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
if not video_url:
|
||||
# 로컬 서빙 경로 (StaticFiles 마운트 기준 상대 경로)
|
||||
try:
|
||||
rel = mp4_path.resolve().relative_to(
|
||||
ssulbox_settings.output_path.resolve()
|
||||
)
|
||||
video_url = f"/ssul-videos/{rel.as_posix()}"
|
||||
except ValueError:
|
||||
logger.error(f"[finalize_task] output 밖 경로 id={content_id} path={mp4_path}")
|
||||
|
||||
row.video_url = video_url
|
||||
# 생성 시점에 이미 채워진 값(검색으로 사용자가 직접 고른 업장)이 우선이다.
|
||||
# 여기 들어오는 값은 생성 로그에서 뒤늦게 주워온 것이므로 덮어쓰지 않는다.
|
||||
if store_name and not row.store_name:
|
||||
row.store_name = store_name
|
||||
if region and not row.region:
|
||||
row.region = region
|
||||
row.status = SsulTaskStatus.DONE.value
|
||||
row.step = 4
|
||||
logger.info(f"[finalize_task] DONE id={content_id} url={video_url}")
|
||||
return row, cleanup
|
||||
|
||||
|
||||
async def fail_task(
|
||||
session: AsyncSession, content_id: int, error: str
|
||||
) -> Optional[SsulContent]:
|
||||
"""실패 처리: 환불(멱등) + status=error. 이미 터미널이면 건너뛴다."""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None:
|
||||
return None
|
||||
if row.status in (SsulTaskStatus.DONE.value, SsulTaskStatus.ERROR.value):
|
||||
return row
|
||||
|
||||
if row.user_uuid: # 탈퇴로 NULL 이 된 경우 환불 대상이 없다
|
||||
await refund_credit_for_job(
|
||||
session=session,
|
||||
user_uuid=row.user_uuid,
|
||||
amount=ssulbox_settings.SSULBOX_CREDITS_PER_VIDEO,
|
||||
job_type=JOB_TYPE_SSUL,
|
||||
job_ref=_job_ref(content_id),
|
||||
reason="썰박스 생성 실패 환불",
|
||||
)
|
||||
|
||||
row.status = SsulTaskStatus.ERROR.value
|
||||
row.error = (error or "생성 실패")[:2000]
|
||||
logger.info(f"[fail_task] id={content_id} error={row.error[:80]}")
|
||||
return row
|
||||
|
||||
|
||||
async def get_place_info(
|
||||
session: AsyncSession, content_id: int
|
||||
) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""(store_name, region, detail_region_info).
|
||||
|
||||
크롤링으로 채울 값이 남았는지 판단하는 데 쓴다.
|
||||
"""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None:
|
||||
return None, None, None
|
||||
return row.store_name, row.region, row.detail_region_info
|
||||
|
||||
|
||||
async def set_place_info(
|
||||
session: AsyncSession,
|
||||
content_id: int,
|
||||
*,
|
||||
store_name: Optional[str] = None,
|
||||
region: Optional[str] = None,
|
||||
detail_region_info: Optional[str] = None,
|
||||
) -> Optional[SsulContent]:
|
||||
"""크롤링으로 얻은 업장 정보를 채운다. **이미 있는 값은 덮지 않는다.**
|
||||
|
||||
사용자가 검색으로 직접 고른 값이 크롤링 추정치보다 정확하므로 우선한다.
|
||||
"""
|
||||
row = await session.get(SsulContent, content_id)
|
||||
if row is None:
|
||||
return None
|
||||
if store_name and not row.store_name:
|
||||
row.store_name = store_name
|
||||
if region and not row.region:
|
||||
row.region = region
|
||||
if detail_region_info and not row.detail_region_info:
|
||||
row.detail_region_info = detail_region_info
|
||||
logger.info(
|
||||
f"[set_place_info] id={content_id} store={row.store_name!r} "
|
||||
f"region={row.region!r} detail={(row.detail_region_info or '')[:30]!r}"
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def sweep_orphans(session: AsyncSession) -> int:
|
||||
"""기동 시 고아 잡 정리 — 환불 + error.
|
||||
|
||||
불변식: 프로세스 기동 직후 인메모리 잡은 0개이므로 DB 의 queued/running 은
|
||||
**전부 이전 프로세스의 고아**다. finalize 가 단일 트랜잭션이라
|
||||
"영상은 만들어졌는데 running" 같은 중간 상태는 존재하지 않는다.
|
||||
|
||||
⚠️ 이 불변식은 **단일 워커 전제**다. `--workers` 를 늘리면 워커 B 가 기동하며
|
||||
워커 A 가 지금 돌리는 잡을 고아로 오판해 환불·error 처리한다.
|
||||
"""
|
||||
rows = (
|
||||
(
|
||||
await session.execute(
|
||||
select(SsulContent).where(SsulContent.status.in_(ORPHAN_STATUSES))
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
if row.user_uuid:
|
||||
await refund_credit_for_job(
|
||||
session=session,
|
||||
user_uuid=row.user_uuid,
|
||||
amount=ssulbox_settings.SSULBOX_CREDITS_PER_VIDEO,
|
||||
job_type=JOB_TYPE_SSUL,
|
||||
job_ref=_job_ref(row.id),
|
||||
reason="서버 재시작 환불",
|
||||
)
|
||||
row.status = SsulTaskStatus.ERROR.value
|
||||
row.error = "서버 재시작으로 중단되었습니다. 크레딧은 환불되었습니다."
|
||||
if rows:
|
||||
logger.info(f"[sweep_orphans] 고아 {len(rows)}건 환불·정리")
|
||||
return len(rows)
|
||||
|
||||
|
||||
def cleanup_job_dir(job_dir: Optional[Path]) -> None:
|
||||
"""생성 산출물 폴더 삭제. **커밋이 성공한 뒤에만** 호출할 것."""
|
||||
if not job_dir or not job_dir.exists():
|
||||
return
|
||||
try:
|
||||
shutil.rmtree(job_dir)
|
||||
logger.info(f"[cleanup_job_dir] 삭제 {job_dir}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[cleanup_job_dir] 삭제 실패 {job_dir} - {e}")
|
||||
Reference in new issue
Block a user