feat(ssulbox): 썰박스 생성 파이프라인 통합 및 콘텐츠 목록 UNION

This commit is contained in:
skkim committed 2026-08-11 11:03:03 +09:00
1 parent 8096837b13
commit 666c3bf6d1
77 files changed
+15912 -349

No files matched your search

+3 -1
View File
@@ -6,7 +6,9 @@ from app.core.exceptions import FastShipError
class InsufficientCreditError(FastShipError):
"""크레딧이 부족합니다."""
status = status.HTTP_400_BAD_REQUEST
# 402 Payment Required. 사전차감 전환 전에는 라우터로 노출된 적이 없어(내부에서만
# raise/catch) 400 이었다. 프론트가 "충전 화면으로 유도"를 402 로 분기한다.
status = status.HTTP_402_PAYMENT_REQUIRED
class InvalidRequestStateError(FastShipError):
+33 -1
View File
@@ -2,7 +2,16 @@ from datetime import datetime
from enum import Enum
from typing import TYPE_CHECKING, Optional
from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, func
from sqlalchemy import (
BigInteger,
DateTime,
ForeignKey,
Index,
Integer,
String,
UniqueConstraint,
func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database.session import Base
@@ -146,6 +155,10 @@ class CreditTransaction(Base):
Index("idx_credit_tx_user_uuid_created", "user_uuid", "created_at"),
Index("idx_credit_tx_type", "type"),
Index("idx_credit_tx_related_request", "related_request_id"),
# 작업 1건당 consume 1행 / refund 1행을 DB 레벨에서 보장하는 멱등 키.
# MySQL 은 NULL 을 서로 다르게 취급하므로 job_type 이 NULL 인 기존
# charge/admin_adjust 행은 이 제약의 영향을 받지 않는다.
UniqueConstraint("job_type", "job_ref", "type", name="uq_credit_job"),
{
"mysql_engine": "InnoDB",
"mysql_charset": "utf8mb4",
@@ -206,6 +219,25 @@ class CreditTransaction(Base):
comment="연관 충전 요청 ID",
)
# ==========================================================================
# 작업 기반 멱등 키 — (job_type, job_ref, type) 유니크
# ==========================================================================
# 사전차감 정책의 핵심. 생성 작업을 시작할 때 차감하고 실패 시 환불하는데,
# 재시도·중복 요청·크래시 후 재처리에도 "작업 1건당 정확히 1번"을 보장해야 한다.
# FK 를 걸지 않는 이유: 썰박스(ssul_task.id 숫자)와 영상(video.task_id UUID7 문자열)
# 이라는 이질적인 두 작업 테이블을 하나의 컬럼이 가리키기 때문이다.
job_type: Mapped[Optional[str]] = mapped_column(
String(20),
nullable=True,
comment="차감 유발 작업 종류 (ssul/video). 충전·관리자 조정은 NULL",
)
job_ref: Mapped[Optional[str]] = mapped_column(
String(64),
nullable=True,
comment="작업 식별자 (ssul_task.id 문자열 또는 video.task_id)",
)
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
+187
View File
@@ -32,6 +32,8 @@ async def record_transaction(
reason: Optional[str] = None,
admin_id: Optional[int] = None,
related_request_id: Optional[int] = None,
job_type: Optional[str] = None,
job_ref: Optional[str] = None,
) -> CreditTransaction:
tx = CreditTransaction(
user_uuid=user_uuid,
@@ -41,6 +43,8 @@ async def record_transaction(
reason=reason,
admin_id=admin_id,
related_request_id=related_request_id,
job_type=job_type,
job_ref=job_ref,
)
session.add(tx)
await session.flush()
@@ -123,6 +127,189 @@ async def deduct_credit(
return tx
# =============================================================================
# 작업 기반 차감/환불 (사전차감 정책)
# =============================================================================
# 위의 charge_credit / deduct_credit 은 멱등성이 없어 재시도 시 중복 반영된다.
# 생성 작업처럼 "시작할 때 차감하고 실패하면 환불"하는 경로에서는 아래 두 함수를 쓴다.
#
# 멱등 보장 방식은 2중이다:
# 1) 먼저 (job_type, job_ref, type) 로 기존 행을 조회해 있으면 그대로 반환
# 2) 경합으로 1)을 통과한 두 요청이 동시에 INSERT 하면 DB 유니크 제약이 막는다
# 잔액 자체는 User 행을 with_for_update() 로 잠근 뒤 읽기→갱신하므로 경합에 안전하다.
#
# 두 함수 모두 **자체 commit 하지 않는다.** 호출부가 트랜잭션을 소유하고,
# 작업 행 생성과 차감을 한 트랜잭션으로 묶어 마지막에 한 번만 커밋해야 한다.
async def _find_job_transaction(
session: AsyncSession,
job_type: str,
job_ref: str,
type: CreditTransactionType,
) -> Optional[CreditTransaction]:
"""(job_type, job_ref, type) 에 해당하는 기존 원장 행 조회"""
result = await session.execute(
select(CreditTransaction).where(
CreditTransaction.job_type == job_type,
CreditTransaction.job_ref == job_ref,
CreditTransaction.type == type,
)
)
return result.scalar_one_or_none()
async def deduct_credit_for_job(
*,
session: AsyncSession,
user_uuid: str,
amount: int,
job_type: str,
job_ref: str,
reason: Optional[str] = None,
) -> CreditTransaction:
"""작업 시작 시점에 크레딧을 선차감한다. (job_type, job_ref) 기준 멱등.
Args:
session: 호출부가 소유하는 세션. 이 함수는 commit 하지 않는다.
user_uuid: 사용자 UUID
amount: 차감할 크레딧 (양수)
job_type: 작업 종류 ("video" | "ssul")
job_ref: 작업 식별자 (video.task_id 또는 str(ssul_task.id))
reason: 원장에 남길 사유
Returns:
새로 만든 차감 원장 행. 이미 차감된 작업이면 기존 행을 그대로 반환한다.
Raises:
InsufficientCreditError: 잔액 부족 (호출부에서 402 로 변환할 것)
UserNotFoundError: 사용자 없음
"""
from app.user.models import User
existing = await _find_job_transaction(
session, job_type, job_ref, CreditTransactionType.CONSUME
)
if existing is not None:
logger.info(
f"[CREDIT] deduct skipped (already charged) "
f"job={job_type}:{job_ref} tx_id={existing.id}"
)
return existing
result = await session.execute(
select(User).where(User.user_uuid == user_uuid).with_for_update()
)
user = result.scalar_one_or_none()
if user is None:
from app.user.services.auth import UserNotFoundError
raise UserNotFoundError()
if user.credits < amount:
logger.warning(
f"[CREDIT] insufficient credits user_uuid={user_uuid} "
f"credits={user.credits} requested={amount} job={job_type}:{job_ref}"
)
raise InsufficientCreditError()
user.credits = user.credits - amount
await session.flush()
tx = await record_transaction(
session=session,
user_uuid=user_uuid,
amount=-amount,
balance_after=user.credits,
type=CreditTransactionType.CONSUME,
reason=reason,
job_type=job_type,
job_ref=job_ref,
)
logger.info(
f"[CREDIT] deduct user_uuid={user_uuid} amount=-{amount} "
f"balance_after={user.credits} job={job_type}:{job_ref}"
)
return tx
async def refund_credit_for_job(
*,
session: AsyncSession,
user_uuid: str,
amount: int,
job_type: str,
job_ref: str,
reason: Optional[str] = None,
) -> Optional[CreditTransaction]:
"""작업 실패 시 선차감한 크레딧을 환불한다. (job_type, job_ref) 기준 멱등.
차감 기록이 없으면 환불하지 않는다 — 애초에 차감되지 않은 작업(예: 정책 전환
이전에 시작된 in-flight 작업)에 환불을 얹으면 크레딧이 늘어나기 때문이다.
Args:
session: 호출부가 소유하는 세션. 이 함수는 commit 하지 않는다.
user_uuid: 사용자 UUID
amount: 환불할 크레딧 (양수)
job_type: 작업 종류 ("video" | "ssul")
job_ref: 작업 식별자
reason: 원장에 남길 사유
Returns:
새로 만든 환불 원장 행. 이미 환불했거나 차감 기록이 없으면 None.
"""
from app.user.models import User
already = await _find_job_transaction(
session, job_type, job_ref, CreditTransactionType.REFUND
)
if already is not None:
logger.info(
f"[CREDIT] refund skipped (already refunded) "
f"job={job_type}:{job_ref} tx_id={already.id}"
)
return None
consumed = await _find_job_transaction(
session, job_type, job_ref, CreditTransactionType.CONSUME
)
if consumed is None:
logger.info(
f"[CREDIT] refund skipped (never charged) job={job_type}:{job_ref}"
)
return None
result = await session.execute(
select(User).where(User.user_uuid == user_uuid).with_for_update()
)
user = result.scalar_one_or_none()
if user is None:
logger.warning(
f"[CREDIT] refund skipped (user not found) "
f"user_uuid={user_uuid} job={job_type}:{job_ref}"
)
return None
user.credits = user.credits + amount
await session.flush()
tx = await record_transaction(
session=session,
user_uuid=user_uuid,
amount=amount,
balance_after=user.credits,
type=CreditTransactionType.REFUND,
reason=reason,
job_type=job_type,
job_ref=job_ref,
)
logger.info(
f"[CREDIT] refund user_uuid={user_uuid} amount=+{amount} "
f"balance_after={user.credits} job={job_type}:{job_ref}"
)
return tx
async def approve_charge_request(
*,
session: AsyncSession,