feat: 좋아요·댓글·SNS 업로드를 콘텐츠 종류 공용으로 통합
This commit is contained in:
1 parent
ed1ba71bfe
commit
fb8febe462
7 files changed
+318
-109
No files matched your search
@@ -42,6 +42,7 @@ from app.database.like_cache import (
|
||||
from app.credit.exceptions import InsufficientCreditError
|
||||
from app.credit.services.credit_service import deduct_credit_for_job
|
||||
from app.ssulbox.constants import JOB_TYPE_VIDEO as CREDIT_JOB_TYPE_VIDEO
|
||||
from app.ssulbox.models import SsulContent
|
||||
from app.utils.logger import get_logger
|
||||
from app.video.models import Video, VideoReaction
|
||||
from app.video.services import unified_list
|
||||
@@ -55,7 +56,10 @@ from app.video.schemas.video_schema import (
|
||||
VideoRenderData,
|
||||
VideoThumbnailItem,
|
||||
)
|
||||
from app.video.worker.video_task import download_and_upload_video_to_blob
|
||||
from app.video.worker.video_task import (
|
||||
_fail_and_refund,
|
||||
download_and_upload_video_to_blob,
|
||||
)
|
||||
|
||||
|
||||
from config import creatomate_settings
|
||||
@@ -181,10 +185,17 @@ async def generate_video(
|
||||
# ===== 순차 쿼리 실행: Project, MarketingIntel, Lyric, Song, Image =====
|
||||
# Note: AsyncSession은 동일 세션에서 병렬 쿼리를 지원하지 않음
|
||||
|
||||
# Project 조회
|
||||
# Project 조회 (본인 소유만).
|
||||
# ⚠️ task_id 는 경로 파라미터라 남의 값을 넣을 수 있다. 소유자를 안 거르면
|
||||
# 남의 프로젝트로 영상을 만들 수 있고, 더 나쁘게는 크레딧 원장에
|
||||
# job_ref=피해자 task_id 로 차감이 기록돼 **피해자의 정상 생성이
|
||||
# "이미 차감됨"으로 처리**된다(멱등 키 오염).
|
||||
project_result = await session.execute(
|
||||
select(Project)
|
||||
.where(Project.task_id == task_id)
|
||||
.where(
|
||||
Project.task_id == task_id,
|
||||
Project.user_uuid == current_user.user_uuid,
|
||||
)
|
||||
.order_by(Project.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
@@ -521,17 +532,13 @@ async def generate_video(
|
||||
)
|
||||
import traceback
|
||||
logger.error(traceback.format_exc())
|
||||
# 외부 API 실패 시 Video 상태를 failed로 업데이트
|
||||
from app.database.session import AsyncSessionLocal
|
||||
|
||||
async with AsyncSessionLocal() as update_session:
|
||||
video_result = await update_session.execute(
|
||||
select(Video).where(Video.id == video_id)
|
||||
)
|
||||
video_to_update = video_result.scalar_one_or_none()
|
||||
if video_to_update:
|
||||
video_to_update.status = "failed"
|
||||
await update_session.commit()
|
||||
# 외부 API 실패 시 Video 상태를 failed로 갱신하고, 선차감한 크레딧을 환불한다.
|
||||
# 크레딧은 1단계에서 이미 차감됐으므로 여기서 돌려주지 않으면 그대로 소멸된다.
|
||||
await _fail_and_refund(
|
||||
task_id,
|
||||
user_uuid=current_user.user_uuid,
|
||||
reason="영상 생성 실패 환불 (Creatomate 요청 오류)",
|
||||
)
|
||||
return GenerateVideoResponse(
|
||||
success=False,
|
||||
task_id=task_id,
|
||||
@@ -666,20 +673,41 @@ async def get_video_status(
|
||||
message = status_messages.get(status, f"상태: {status}")
|
||||
|
||||
video_id = None
|
||||
|
||||
# ⚠️ 소유자 검증이 필수다. creatomate_render_id 는 클라이언트가 보내는 값이라
|
||||
# 남의 렌더 ID 로 이 엔드포인트를 부를 수 있다. 소유자를 안 거르면
|
||||
# - 실패 분기: 남의 실패 건으로 **호출자에게 환불**이 나가고(크레딧 탈취),
|
||||
# 원장 멱등 키(job_ref=피해자 task_id)가 소진돼 **피해자의 정당한 환불이 봉쇄**된다.
|
||||
# - 성공 분기: 남의 영상이 **호출자 UUID 경로의 Blob** 으로 업로드된다.
|
||||
# video 에는 user_uuid 가 없으므로(소유권은 project 에 있다) Project 를 조인한다.
|
||||
async def _load_owned_video() -> Video | None:
|
||||
row = (
|
||||
await session.execute(
|
||||
select(Video)
|
||||
.join(Project, Video.project_id == Project.id)
|
||||
.where(
|
||||
Video.creatomate_render_id == creatomate_render_id,
|
||||
Project.user_uuid == current_user.user_uuid,
|
||||
)
|
||||
.order_by(Video.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if row is None:
|
||||
logger.warning(
|
||||
"[get_video_status] 소유자 아님 또는 영상 없음 — 후속 처리 생략, "
|
||||
f"creatomate_render_id: {creatomate_render_id}, "
|
||||
f"user: {current_user.user_uuid}"
|
||||
)
|
||||
return row
|
||||
|
||||
# succeeded 상태인 경우 백그라운드 태스크 실행
|
||||
if status == "succeeded" and video_url:
|
||||
# creatomate_render_id로 Video 조회하여 task_id 가져오기
|
||||
video_result = await session.execute(
|
||||
select(Video)
|
||||
.where(Video.creatomate_render_id == creatomate_render_id)
|
||||
.order_by(Video.created_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
video = video_result.scalar_one_or_none()
|
||||
|
||||
video_id = video.id
|
||||
# creatomate_render_id로 Video 조회하여 task_id 가져오기 (본인 것만)
|
||||
video = await _load_owned_video()
|
||||
|
||||
if video and video.status != "completed":
|
||||
video_id = video.id
|
||||
# 이미 완료된 경우 백그라운드 작업 중복 실행 방지
|
||||
# 백그라운드 태스크로 MP4 다운로드 → Blob 업로드 → DB 업데이트 → 임시 파일 삭제
|
||||
logger.info(
|
||||
@@ -693,9 +721,25 @@ async def get_video_status(
|
||||
user_uuid=current_user.user_uuid,
|
||||
)
|
||||
elif video and video.status == "completed":
|
||||
video_id = video.id
|
||||
logger.debug(
|
||||
f"[get_video_status] SKIPPED - Video already completed, creatomate_render_id: {creatomate_render_id}"
|
||||
)
|
||||
elif status == "failed":
|
||||
# 렌더 실패는 Creatomate 가 명시적으로 알려준 시점에만 알 수 있다.
|
||||
# 크레딧은 generate_video 에서 선차감됐으므로 여기서 돌려줘야 한다.
|
||||
# 조회를 본인 소유로 제한했으므로 환불 대상이 곧 소유자다.
|
||||
video = await _load_owned_video()
|
||||
|
||||
if video:
|
||||
video_id = video.id
|
||||
if video.status != "failed":
|
||||
await _fail_and_refund(
|
||||
video.task_id,
|
||||
creatomate_render_id=creatomate_render_id,
|
||||
user_uuid=current_user.user_uuid,
|
||||
reason="영상 생성 실패 환불 (Creatomate 렌더 실패)",
|
||||
)
|
||||
|
||||
render_data = VideoRenderData(
|
||||
id=result.get("id"),
|
||||
@@ -951,57 +995,77 @@ async def get_all_videos(
|
||||
)
|
||||
async def toggle_like(
|
||||
video_id: int,
|
||||
type: Literal["video", "ssul"] = Query(
|
||||
default="video",
|
||||
description="콘텐츠 종류. video.id 와 ssul_content.id 가 겹치므로 반드시 함께 보낼 것",
|
||||
),
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> LikeToggleResponse:
|
||||
"""영상 좋아요를 토글합니다.
|
||||
"""영상/썰박스 좋아요를 토글합니다.
|
||||
|
||||
Write-Behind 패턴:
|
||||
1. Redis user-set / count를 즉시 원자적으로 업데이트 (Lua script)
|
||||
2. dirty SET에 표시 → 스케줄러가 1분마다 MySQL에 반영
|
||||
DB write가 없으므로 고트래픽에서도 응답 지연 없음.
|
||||
|
||||
두 종류가 같은 테이블(video_reaction)·같은 Redis 로직을 쓰므로 엔드포인트도
|
||||
하나다. type 은 ① 존재 확인 대상 ② Redis 키 접두 ③ backfill 컬럼만 가른다.
|
||||
기본값이 "video" 라 기존 프론트 호출은 수정 없이 동작한다.
|
||||
"""
|
||||
logger.info(f"[toggle_like] START - video_id: {video_id}, user: {current_user.user_uuid}")
|
||||
logger.info(
|
||||
f"[toggle_like] START - type: {type}, id: {video_id}, user: {current_user.user_uuid}"
|
||||
)
|
||||
|
||||
try:
|
||||
# 영상 존재 확인 (DB read는 유지 — 404 처리 필수)
|
||||
video_result = await session.execute(
|
||||
select(Video).where(
|
||||
# 대상 존재 확인 (DB read는 유지 — 404 처리 필수).
|
||||
# id 가 종류별 독립 시퀀스라 반대쪽 테이블에 같은 id 가 있어도 잡으면 안 된다.
|
||||
if type == "ssul":
|
||||
exists_q = select(SsulContent.id).where(
|
||||
SsulContent.id == video_id,
|
||||
SsulContent.status == "done",
|
||||
SsulContent.is_deleted.is_(False),
|
||||
)
|
||||
# DB backfill 시 반응 행을 찾는 컬럼 — 썰박스 행은 content_id 가 채워져 있다
|
||||
target_col = VideoReaction.content_id
|
||||
else:
|
||||
exists_q = select(Video.id).where(
|
||||
Video.id == video_id,
|
||||
Video.status == "completed",
|
||||
Video.is_deleted == False, # noqa: E712
|
||||
Video.is_deleted.is_(False),
|
||||
)
|
||||
)
|
||||
if video_result.scalar_one_or_none() is None:
|
||||
raise HTTPException(status_code=404, detail="영상을 찾을 수 없습니다.")
|
||||
target_col = VideoReaction.video_id
|
||||
|
||||
if (await session.execute(exists_q)).scalar_one_or_none() is None:
|
||||
raise HTTPException(status_code=404, detail="콘텐츠를 찾을 수 없습니다.")
|
||||
|
||||
# Cold-start 보정: Redis에 데이터가 없으면 DB에서 backfill
|
||||
count = await get_like_count(video_id)
|
||||
count = await get_like_count(video_id, ctype=type)
|
||||
if count is None:
|
||||
# 카운트와 user-set 모두 없음 → DB에서 전체 복구
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
select(VideoReaction.user_uuid).where(target_col == video_id)
|
||||
)).scalars().all()
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
await set_like_count(video_id, len(user_uuids))
|
||||
await backfill_user_set(video_id, list(user_uuids), ctype=type)
|
||||
await set_like_count(video_id, len(user_uuids), ctype=type)
|
||||
elif count > 0:
|
||||
if not await is_user_set_exists(video_id):
|
||||
if not await is_user_set_exists(video_id, ctype=type):
|
||||
# 카운트는 있지만 user-set이 증발한 경우 (부분 캐시 미스)
|
||||
user_uuids = (await session.execute(
|
||||
select(VideoReaction.user_uuid)
|
||||
.where(VideoReaction.video_id == video_id)
|
||||
select(VideoReaction.user_uuid).where(target_col == video_id)
|
||||
)).scalars().all()
|
||||
await backfill_user_set(video_id, list(user_uuids))
|
||||
await backfill_user_set(video_id, list(user_uuids), ctype=type)
|
||||
|
||||
# Lua 스크립트로 원자적 토글 (race condition 방지)
|
||||
is_liked, like_count = await toggle_like_atomic(video_id, current_user.user_uuid)
|
||||
is_liked, like_count = await toggle_like_atomic(
|
||||
video_id, current_user.user_uuid, ctype=type
|
||||
)
|
||||
|
||||
# dirty SET에 표시 → 스케줄러가 DB에 반영
|
||||
await mark_dirty(video_id, current_user.user_uuid)
|
||||
await mark_dirty(video_id, current_user.user_uuid, ctype=type)
|
||||
|
||||
logger.info(
|
||||
f"[toggle_like] SUCCESS - video_id: {video_id}, "
|
||||
f"[toggle_like] SUCCESS - type: {type}, id: {video_id}, "
|
||||
f"is_liked: {is_liked}, count: {like_count}"
|
||||
)
|
||||
return LikeToggleResponse(video_id=video_id, is_liked=is_liked, like_count=like_count)
|
||||
|
||||
Reference in new issue
Block a user