Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8096837b13 | ||
|
|
5903211eb9 | ||
|
|
68fc5ebca6 | ||
|
|
cbc3f47b54 |
No files matched your search
@@ -433,6 +433,10 @@ class YouTubeAnalyticsService:
|
|||||||
logger.debug("[YouTubeAnalyticsService._fetch_region] SUCCESS")
|
logger.debug("[YouTubeAnalyticsService._fetch_region] SUCCESS")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
# 5xx/네트워크 오류 재시도 설정 (구글 backendError 등 일시적 장애 대응)
|
||||||
|
_MAX_RETRIES = 3
|
||||||
|
_RETRY_BACKOFF_SECONDS = (0.5, 1.0, 2.0)
|
||||||
|
|
||||||
async def _call_api(
|
async def _call_api(
|
||||||
self,
|
self,
|
||||||
params: dict[str, str],
|
params: dict[str, str],
|
||||||
@@ -453,51 +457,67 @@ class YouTubeAnalyticsService:
|
|||||||
Raises:
|
Raises:
|
||||||
YouTubeQuotaExceededError: 할당량 초과 (429)
|
YouTubeQuotaExceededError: 할당량 초과 (429)
|
||||||
YouTubeAuthError: 인증 실패 (401, 403)
|
YouTubeAuthError: 인증 실패 (401, 403)
|
||||||
YouTubeAPIError: 기타 API 오류
|
YouTubeAPIError: 기타 API 오류 (5xx/네트워크 오류는 최대 3회 재시도 후 발생)
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
- 타임아웃: 30초
|
- 타임아웃: 30초
|
||||||
- 할당량 초과 시 자동으로 YouTubeQuotaExceededError 발생
|
- 할당량 초과 시 자동으로 YouTubeQuotaExceededError 발생
|
||||||
- 인증 실패 시 자동으로 YouTubeAuthError 발생
|
- 인증 실패 시 자동으로 YouTubeAuthError 발생
|
||||||
|
- 5xx 응답 및 네트워크 오류는 지수 백오프(0.5s→1s→2s)로 최대 3회 재시도
|
||||||
"""
|
"""
|
||||||
headers = {"Authorization": f"Bearer {access_token}"}
|
headers = {"Authorization": f"Bearer {access_token}"}
|
||||||
|
|
||||||
try:
|
last_error: Exception | None = None
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
for attempt in range(self._MAX_RETRIES + 1):
|
||||||
response = await client.get(
|
try:
|
||||||
self.BASE_URL,
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
params=params,
|
response = await client.get(
|
||||||
headers=headers,
|
self.BASE_URL,
|
||||||
)
|
params=params,
|
||||||
|
headers=headers,
|
||||||
# 할당량 초과 체크
|
|
||||||
if response.status_code == 429:
|
|
||||||
logger.warning("[YouTubeAnalyticsService._call_api] QUOTA_EXCEEDED")
|
|
||||||
raise YouTubeQuotaExceededError()
|
|
||||||
|
|
||||||
# 인증 실패 체크
|
|
||||||
if response.status_code in (401, 403):
|
|
||||||
logger.warning(
|
|
||||||
f"[YouTubeAnalyticsService._call_api] AUTH_FAILED - status={response.status_code}"
|
|
||||||
)
|
)
|
||||||
raise YouTubeAuthError(f"YouTube 인증 실패: {response.status_code}")
|
|
||||||
|
|
||||||
# HTTP 에러 체크
|
# 할당량 초과 체크
|
||||||
response.raise_for_status()
|
if response.status_code == 429:
|
||||||
|
logger.warning("[YouTubeAnalyticsService._call_api] QUOTA_EXCEEDED")
|
||||||
|
raise YouTubeQuotaExceededError()
|
||||||
|
|
||||||
return response.json()
|
# 인증 실패 체크
|
||||||
|
if response.status_code in (401, 403):
|
||||||
|
logger.warning(
|
||||||
|
f"[YouTubeAnalyticsService._call_api] AUTH_FAILED - status={response.status_code}"
|
||||||
|
)
|
||||||
|
raise YouTubeAuthError(f"YouTube 인증 실패: {response.status_code}")
|
||||||
|
|
||||||
except (YouTubeAuthError, YouTubeQuotaExceededError):
|
# HTTP 에러 체크
|
||||||
raise # 이미 처리된 예외는 그대로 전파
|
response.raise_for_status()
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error(
|
return response.json()
|
||||||
f"[YouTubeAnalyticsService._call_api] HTTP_ERROR - "
|
|
||||||
f"status={e.response.status_code}, body={e.response.text[:500]}"
|
except (YouTubeAuthError, YouTubeQuotaExceededError):
|
||||||
)
|
raise # 이미 처리된 예외는 재시도 없이 그대로 전파
|
||||||
raise YouTubeAPIError(f"HTTP {e.response.status_code}")
|
except httpx.HTTPStatusError as e:
|
||||||
except httpx.RequestError as e:
|
logger.error(
|
||||||
logger.error(f"[YouTubeAnalyticsService._call_api] REQUEST_ERROR - {e}")
|
f"[YouTubeAnalyticsService._call_api] HTTP_ERROR - "
|
||||||
raise YouTubeAPIError(f"네트워크 오류: {e}")
|
f"status={e.response.status_code}, body={e.response.text[:500]}"
|
||||||
except Exception as e:
|
)
|
||||||
logger.error(f"[YouTubeAnalyticsService._call_api] UNEXPECTED_ERROR - {e}")
|
# 4xx는 재시도해도 동일하게 실패하므로 즉시 전파, 5xx만 재시도
|
||||||
raise YouTubeAPIError(f"알 수 없는 오류: {e}")
|
if e.response.status_code < 500:
|
||||||
|
raise YouTubeAPIError(f"HTTP {e.response.status_code}")
|
||||||
|
last_error = YouTubeAPIError(f"HTTP {e.response.status_code}")
|
||||||
|
except httpx.RequestError as e:
|
||||||
|
logger.error(f"[YouTubeAnalyticsService._call_api] REQUEST_ERROR - {e}")
|
||||||
|
last_error = YouTubeAPIError(f"네트워크 오류: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[YouTubeAnalyticsService._call_api] UNEXPECTED_ERROR - {e}")
|
||||||
|
raise YouTubeAPIError(f"알 수 없는 오류: {e}")
|
||||||
|
|
||||||
|
if attempt < self._MAX_RETRIES:
|
||||||
|
backoff = self._RETRY_BACKOFF_SECONDS[attempt]
|
||||||
|
logger.warning(
|
||||||
|
f"[YouTubeAnalyticsService._call_api] RETRY {attempt + 1}/{self._MAX_RETRIES} "
|
||||||
|
f"in {backoff}s - {last_error}"
|
||||||
|
)
|
||||||
|
await asyncio.sleep(backoff)
|
||||||
|
|
||||||
|
raise last_error
|
||||||
+12
-5
@@ -151,11 +151,18 @@ async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
|||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await session.rollback()
|
await session.rollback()
|
||||||
logger.error(traceback.format_exc())
|
# status_code < 500인 도메인 예외(계정 미연동 등)는 정상적인 비즈니스 흐름이므로 ERROR로 남기지 않음
|
||||||
logger.error(
|
if getattr(e, "status_code", 500) < 500:
|
||||||
f"[get_session] ROLLBACK - error: {type(e).__name__}: {e}, "
|
logger.warning(
|
||||||
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
|
f"[get_session] ROLLBACK - client error: {type(e).__name__}: {e}, "
|
||||||
)
|
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.error(traceback.format_exc())
|
||||||
|
logger.error(
|
||||||
|
f"[get_session] ROLLBACK - error: {type(e).__name__}: {e}, "
|
||||||
|
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
|
||||||
|
)
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
total_time = time.perf_counter() - start_time
|
total_time = time.perf_counter() - start_time
|
||||||
|
|||||||
@@ -70,11 +70,11 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
language: str = Field(
|
language: str = Field(
|
||||||
default="Korean",
|
default="Korean",
|
||||||
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
|
description="가사 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)",
|
||||||
),
|
)
|
||||||
orientation: Literal["horizontal", "vertical"] = Field(
|
orientation: Literal["horizontal", "vertical"] = Field(
|
||||||
default="vertical",
|
default="vertical",
|
||||||
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
||||||
),
|
)
|
||||||
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
m_id : Optional[int] = Field(None, description="마케팅 인텔리전스 ID 값")
|
||||||
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general)")
|
industry: str = Field(default="", description="업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction|general)")
|
||||||
instrumental: bool = Field(default=False, description="BGM 전용 모드 (가사 생성 안 함)")
|
instrumental: bool = Field(default=False, description="BGM 전용 모드 (가사 생성 안 함)")
|
||||||
@@ -83,11 +83,6 @@ class GenerateLyricRequest(BaseModel):
|
|||||||
description="사용자가 수동으로 고른 음악 장르 (kpop|pop|ballad|hip-hop|rnb|edm|jazz|rock). "
|
description="사용자가 수동으로 고른 음악 장르 (kpop|pop|ballad|hip-hop|rnb|edm|jazz|rock). "
|
||||||
"'자동 선택'인 경우 None으로 전달하면 GPT가 가사 무드에 맞춰 추천",
|
"'자동 선택'인 경우 None으로 전달하면 GPT가 가사 무드에 맞춰 추천",
|
||||||
)
|
)
|
||||||
genre: Optional[str] = Field(
|
|
||||||
None,
|
|
||||||
description="사용자가 수동으로 고른 음악 장르 (kpop|pop|ballad|hip-hop|rnb|edm|jazz|rock). "
|
|
||||||
"'자동 선택'인 경우 None으로 전달하면 GPT가 가사 무드에 맞춰 추천",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class GenerateLyricResponse(BaseModel):
|
class GenerateLyricResponse(BaseModel):
|
||||||
|
|||||||
+16
-2
@@ -806,7 +806,7 @@ class CreatomateService:
|
|||||||
"""이미지 슬롯에 대한 각 이미지의 매칭 점수를 계산합니다.
|
"""이미지 슬롯에 대한 각 이미지의 매칭 점수를 계산합니다.
|
||||||
|
|
||||||
점수 = (base * narr_mod + NARR_BONUS * narr) * space_type_penalty
|
점수 = (base * narr_mod + NARR_BONUS * narr) * space_type_penalty
|
||||||
- base: 태그 카테고리 매칭 합산 (최대 5.5)
|
- base: 태그 카테고리 매칭 합산 (최대 6.5 = space_type 2.0 + subject 3.0 + camera 1.0 + motion 0.5)
|
||||||
- narr_mod: [NARR_FLOOR, 1.0] 구간으로 완화된 narrative 계수
|
- narr_mod: [NARR_FLOOR, 1.0] 구간으로 완화된 narrative 계수
|
||||||
- NARR_BONUS * narr: narrative 독립 보너스 (base=0이어도 신호 유지)
|
- NARR_BONUS * narr: narrative 독립 보너스 (base=0이어도 신호 유지)
|
||||||
- space_type_penalty: 슬롯이 요구하는 space_type과 이미지가 불일치하면
|
- space_type_penalty: 슬롯이 요구하는 space_type과 이미지가 불일치하면
|
||||||
@@ -830,6 +830,20 @@ class CreatomateService:
|
|||||||
for image_tag in image_tag_list
|
for image_tag in image_tag_list
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# 썸네일 슬롯 한정: subject가 슬롯 요구와 일치하면 space_type 불일치
|
||||||
|
# 페널티를 면제한다. 배경: 일부 업종(예: 레스토랑 dining_hall-food_dish)은
|
||||||
|
# 태깅 관행상 슬롯이 요구하는 subject(음식 클로즈업)가 실제로는 다른
|
||||||
|
# space_type(table_setting/detail_plating 등)으로 붙는다 — space_type과
|
||||||
|
# subject가 한 사진에 공존하기 어려운 조합. 이런 슬롯은 space_type 하드
|
||||||
|
# 필터가 정작 원하는 subject 이미지를 전부 걸러내는 역효과를 낸다.
|
||||||
|
# 템플릿 슬롯명을 바꾸지 않고 여기서 흡수(썸네일 한정이라 일반 씬 슬롯의
|
||||||
|
# space_type 하드 필터는 그대로 유지).
|
||||||
|
slot_subject = slot_tag_dict.get("subject")
|
||||||
|
if slot_name.endswith(THUMBNAIL_SLOT_MARKER) and slot_subject is not None:
|
||||||
|
for idx, image_tag in enumerate(image_tag_list):
|
||||||
|
if slot_subject.value in image_tag.get("subject", []):
|
||||||
|
space_type_match_list[idx] = True
|
||||||
|
|
||||||
for slot_tag_cate, slot_tag_item in slot_tag_dict.items():
|
for slot_tag_cate, slot_tag_item in slot_tag_dict.items():
|
||||||
if slot_tag_cate == "narrative_preference":
|
if slot_tag_cate == "narrative_preference":
|
||||||
slot_tag_narrative = slot_tag_item
|
slot_tag_narrative = slot_tag_item
|
||||||
@@ -839,7 +853,7 @@ class CreatomateService:
|
|||||||
case "space_type":
|
case "space_type":
|
||||||
weight = 2.0
|
weight = 2.0
|
||||||
case "subject":
|
case "subject":
|
||||||
weight = 2.0
|
weight = 3.0
|
||||||
case "camera":
|
case "camera":
|
||||||
weight = 1.0
|
weight = 1.0
|
||||||
case "motion_recommended":
|
case "motion_recommended":
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ Meta 픽셀/Conversions API 전환 이벤트 발화를 위한 엔드포인트를
|
|||||||
app.include_router(router)
|
app.include_router(router)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
@@ -76,13 +77,57 @@ class FirstVideoCreatedResponse(BaseModel):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_public_ip(value: str) -> bool:
|
||||||
|
"""Meta 매칭에 사용 가능한 공인 IP인지 검사합니다.
|
||||||
|
|
||||||
|
사설/루프백 대역(Docker 내부 172.x, 로컬 127.0.0.1 등)을 보내면
|
||||||
|
Meta가 유효하지 않은 값으로 폐기하면서 매개변수 전송률만 깎이므로,
|
||||||
|
공인 IP가 아니면 아예 전송하지 않기 위해 사용합니다.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(value)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return not (
|
||||||
|
ip.is_private
|
||||||
|
or ip.is_loopback
|
||||||
|
or ip.is_link_local
|
||||||
|
or ip.is_reserved
|
||||||
|
or ip.is_multicast
|
||||||
|
or ip.is_unspecified
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _extract_client_ip(request: Request) -> str | None:
|
def _extract_client_ip(request: Request) -> str | None:
|
||||||
"""리버스 프록시 환경을 고려하여 클라이언트 IP를 추출합니다."""
|
"""리버스 프록시 환경을 고려하여 클라이언트 공인 IP를 추출합니다.
|
||||||
|
|
||||||
|
후보를 순서대로 검사하여 처음 발견된 공인 IP를 반환합니다.
|
||||||
|
1. X-Real-IP: nginx가 $remote_addr로 덮어쓰므로 위조 불가 (최우선)
|
||||||
|
2. X-Forwarded-For: 클라이언트가 보낸 값 뒤에 nginx가 덧붙이는 구조라
|
||||||
|
맨 앞 항목이 위조될 수 있으므로, 항목을 순회하며 공인 IP를 찾음
|
||||||
|
3. 소켓 peer 주소: 프록시가 없는 환경 대비
|
||||||
|
|
||||||
|
공인 IP를 하나도 찾지 못하면 None을 반환합니다 (전송 생략).
|
||||||
|
"""
|
||||||
|
candidates: list[str] = []
|
||||||
|
|
||||||
|
real_ip = request.headers.get("x-real-ip")
|
||||||
|
if real_ip:
|
||||||
|
candidates.append(real_ip.strip())
|
||||||
|
|
||||||
forwarded_for = request.headers.get("x-forwarded-for")
|
forwarded_for = request.headers.get("x-forwarded-for")
|
||||||
if forwarded_for:
|
if forwarded_for:
|
||||||
# "client, proxy1, proxy2" 형식에서 최초 클라이언트 IP 사용
|
candidates.extend(part.strip() for part in forwarded_for.split(","))
|
||||||
return forwarded_for.split(",")[0].strip()
|
|
||||||
return request.client.host if request.client else None
|
if request.client:
|
||||||
|
candidates.append(request.client.host)
|
||||||
|
|
||||||
|
for candidate in candidates:
|
||||||
|
if _is_public_ip(candidate):
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@router.post("/meta/first-video-created", response_model=FirstVideoCreatedResponse)
|
@router.post("/meta/first-video-created", response_model=FirstVideoCreatedResponse)
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Migration: 기존 회원의 first_video_created_at 백필
|
||||||
|
-- Date: 2026-07-27
|
||||||
|
-- Description: Meta FirstVideoCreated 전환 이벤트 오발화 방지
|
||||||
|
--
|
||||||
|
-- [문제]
|
||||||
|
-- first_video_created_at은 신규 컬럼이라 기존 회원 전원이 NULL이다.
|
||||||
|
-- FirstVideoCreated 발화 조건은 "completed 영상 존재 + 컬럼이 NULL"이므로,
|
||||||
|
-- 배포 후 기존 회원이 영상을 하나 더 만들면 그것이 51번째 영상이어도
|
||||||
|
-- "첫 영상 생성"으로 발화되어 핵심 전환 이벤트가 오염된다.
|
||||||
|
-- (CompleteRegistration은 is_new_user 게이트 + 24시간 가드가 있어 해당 없음)
|
||||||
|
--
|
||||||
|
-- [조치]
|
||||||
|
-- 이미 completed 영상을 보유한 회원은 그 최초 영상의 생성 시각으로
|
||||||
|
-- 컬럼을 채워 "이미 발화 완료" 상태로 만든다.
|
||||||
|
--
|
||||||
|
-- [실행 시점]
|
||||||
|
-- 반드시 백엔드 배포 전에 실행할 것.
|
||||||
|
-- (ALTER TABLE 마이그레이션 2건을 먼저 적용한 뒤 실행)
|
||||||
|
--
|
||||||
|
-- 관련 코드: app/video/api/routers/v1/tracking.py
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- 백필 대상 건수 사전 확인 (실행 전 참고용)
|
||||||
|
-- SELECT COUNT(*) FROM `user` u
|
||||||
|
-- WHERE u.first_video_created_at IS NULL
|
||||||
|
-- AND EXISTS (
|
||||||
|
-- SELECT 1 FROM video v
|
||||||
|
-- JOIN project p ON v.project_id = p.id
|
||||||
|
-- WHERE p.user_uuid = u.user_uuid AND v.status = 'completed'
|
||||||
|
-- );
|
||||||
|
|
||||||
|
UPDATE `user` u
|
||||||
|
SET u.first_video_created_at = (
|
||||||
|
SELECT MIN(v.created_at)
|
||||||
|
FROM video v
|
||||||
|
JOIN project p ON v.project_id = p.id
|
||||||
|
WHERE p.user_uuid = u.user_uuid
|
||||||
|
AND v.status = 'completed'
|
||||||
|
)
|
||||||
|
WHERE u.first_video_created_at IS NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM video v
|
||||||
|
JOIN project p ON v.project_id = p.id
|
||||||
|
WHERE p.user_uuid = u.user_uuid
|
||||||
|
AND v.status = 'completed'
|
||||||
|
);
|
||||||
Reference in new issue
Block a user