add logs for tracing processing task

This commit is contained in:
Dohyun Lim committed 2026-01-08 14:05:44 +09:00
1 parent efddee217a
commit 073777081e
81 files changed
+25300 -24561

No files matched your search

+29 -29
View File
@@ -1,30 +1,30 @@
from uuid import UUID
from redis.asyncio import Redis
from app.config import db_settings
_token_blacklist = Redis(
host=db_settings.REDIS_HOST,
port=db_settings.REDIS_PORT,
db=0,
)
_shipment_verification_codes = Redis(
host=db_settings.REDIS_HOST,
port=db_settings.REDIS_PORT,
db=1,
decode_responses=True,
)
async def add_jti_to_blacklist(jti: str):
await _token_blacklist.set(jti, "blacklisted")
async def is_jti_blacklisted(jti: str) -> bool:
return await _token_blacklist.exists(jti)
async def add_shipment_verification_code(id: UUID, code: int):
await _shipment_verification_codes.set(str(id), code)
async def get_shipment_verification_code(id: UUID) -> str:
from uuid import UUID
from redis.asyncio import Redis
from app.config import db_settings
_token_blacklist = Redis(
host=db_settings.REDIS_HOST,
port=db_settings.REDIS_PORT,
db=0,
)
_shipment_verification_codes = Redis(
host=db_settings.REDIS_HOST,
port=db_settings.REDIS_PORT,
db=1,
decode_responses=True,
)
async def add_jti_to_blacklist(jti: str):
await _token_blacklist.set(jti, "blacklisted")
async def is_jti_blacklisted(jti: str) -> bool:
return await _token_blacklist.exists(jti)
async def add_shipment_verification_code(id: UUID, code: int):
await _shipment_verification_codes.set(str(id), code)
async def get_shipment_verification_code(id: UUID) -> str:
return str(await _shipment_verification_codes.get(str(id)))
+97 -97
View File
@@ -1,97 +1,97 @@
from asyncio import current_task
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.pool import AsyncQueuePool # 비동기 풀 클래스
from config import db_settings
# Base 클래스 정의
class Base(DeclarativeBase):
pass
engine = create_async_engine(
# MySQL async URL (asyncmy 드라이버)
url=db_settings.MYSQL_URL, # 예: "mysql+asyncmy://test:test@host:3306/poc"
# === Connection Pool 설정 ===
pool_size=10, # 기본 풀 크기: 10개 연결 유지
max_overflow=10, # 최대 증가: 10개 (총 20개까지 가능)
poolclass=AsyncQueuePool, # 비동기 큐 풀 사용 (기본값, 명시적 지정)
pool_timeout=30, # 풀에서 연결 대기 시간: 30초 (기본 30초)
pool_recycle=3600, # 연결 재사용 주기: 1시간 (기본 3600초)
pool_pre_ping=True, # 연결 사용 전 유효성 검사: True로 설정
pool_reset_on_return="rollback", # 연결 반환 시 자동 롤백
# === MySQL 특화 설정 ===
echo=False, # SQL 쿼리 로깅 (디버깅 시 True)
# === 연결 타임아웃 및 재시도 ===
connect_args={
"connect_timeout": 10, # MySQL 연결 타임아웃: 10초
"read_timeout": 30, # 읽기 타임아웃: 30초
"write_timeout": 30, # 쓰기 타임아웃: 30초
"charset": "utf8mb4", # 문자셋 (이모지 지원)
"sql_mode": "STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE",
"init_command": "SET SESSION time_zone = '+00:00'", # 초기 연결 시 실행
},
)
# Async 세션 팩토리 생성
async_session_factory = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False, # 커밋 후 객체 상태 유지
autoflush=True, # 변경 감지 자동 플러시
)
# async_scoped_session 생성
AsyncScopedSession = async_session_factory(
async_session_factory,
scopefunc=current_task,
)
# 테이블 생성 함수
async def create_db_tables() -> None:
async with engine.begin() as conn:
# from app.database.models import Shipment, Seller # noqa: F401
await conn.run_sync(Base.metadata.create_all)
print("MySQL tables created successfully")
# 세션 제너레이터 (FastAPI Depends에 사용)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
"""
Async 세션 컨텍스트 매니저
- FastAPI dependency로 사용
- Connection Pool에서 연결 획득/반환 자동 관리
"""
async with async_session_factory() as session:
# pre-commit 훅 (선택적: 트랜잭션 시작 전 실행)
# await session.begin() # async_sessionmaker에서 자동 begin
try:
yield session
# FastAPI 요청 완료 시 자동 commit (예외 발생 시 rollback)
except Exception as e:
await session.rollback() # 명시적 롤백 (선택적)
print(f"Session rollback due to: {e}") # 로깅
raise
finally:
# 명시적 세션 종료 (Connection Pool에 반환)
# context manager가 자동 처리하지만, 명시적으로 유지
await session.close()
print("session closed successfully")
# 또는 session.aclose() - Python 3.10+
# 애플리케이션 종료 시 엔진 정리 (선택적)
async def dispose_engine() -> None:
"""애플리케이션 종료 시 모든 연결 해제"""
await engine.dispose()
print("Database engine disposed")
from asyncio import current_task
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.pool import AsyncQueuePool # 비동기 풀 클래스
from config import db_settings
# Base 클래스 정의
class Base(DeclarativeBase):
pass
engine = create_async_engine(
# MySQL async URL (asyncmy 드라이버)
url=db_settings.MYSQL_URL, # 예: "mysql+asyncmy://test:test@host:3306/poc"
# === Connection Pool 설정 ===
pool_size=10, # 기본 풀 크기: 10개 연결 유지
max_overflow=10, # 최대 증가: 10개 (총 20개까지 가능)
poolclass=AsyncQueuePool, # 비동기 큐 풀 사용 (기본값, 명시적 지정)
pool_timeout=30, # 풀에서 연결 대기 시간: 30초 (기본 30초)
pool_recycle=3600, # 연결 재사용 주기: 1시간 (기본 3600초)
pool_pre_ping=True, # 연결 사용 전 유효성 검사: True로 설정
pool_reset_on_return="rollback", # 연결 반환 시 자동 롤백
# === MySQL 특화 설정 ===
echo=False, # SQL 쿼리 로깅 (디버깅 시 True)
# === 연결 타임아웃 및 재시도 ===
connect_args={
"connect_timeout": 10, # MySQL 연결 타임아웃: 10초
"read_timeout": 30, # 읽기 타임아웃: 30초
"write_timeout": 30, # 쓰기 타임아웃: 30초
"charset": "utf8mb4", # 문자셋 (이모지 지원)
"sql_mode": "STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE",
"init_command": "SET SESSION time_zone = '+00:00'", # 초기 연결 시 실행
},
)
# Async 세션 팩토리 생성
async_session_factory = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False, # 커밋 후 객체 상태 유지
autoflush=True, # 변경 감지 자동 플러시
)
# async_scoped_session 생성
AsyncScopedSession = async_session_factory(
async_session_factory,
scopefunc=current_task,
)
# 테이블 생성 함수
async def create_db_tables() -> None:
async with engine.begin() as conn:
# from app.database.models import Shipment, Seller # noqa: F401
await conn.run_sync(Base.metadata.create_all)
print("MySQL tables created successfully")
# 세션 제너레이터 (FastAPI Depends에 사용)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
"""
Async 세션 컨텍스트 매니저
- FastAPI dependency로 사용
- Connection Pool에서 연결 획득/반환 자동 관리
"""
async with async_session_factory() as session:
# pre-commit 훅 (선택적: 트랜잭션 시작 전 실행)
# await session.begin() # async_sessionmaker에서 자동 begin
try:
yield session
# FastAPI 요청 완료 시 자동 commit (예외 발생 시 rollback)
except Exception as e:
await session.rollback() # 명시적 롤백 (선택적)
print(f"Session rollback due to: {e}") # 로깅
raise
finally:
# 명시적 세션 종료 (Connection Pool에 반환)
# context manager가 자동 처리하지만, 명시적으로 유지
await session.close()
print("session closed successfully")
# 또는 session.aclose() - Python 3.10+
# 애플리케이션 종료 시 엔진 정리 (선택적)
async def dispose_engine() -> None:
"""애플리케이션 종료 시 모든 연결 해제"""
await engine.dispose()
print("Database engine disposed")
+161 -161
View File
@@ -1,161 +1,161 @@
import time
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from config import db_settings
class Base(DeclarativeBase):
pass
# =============================================================================
# 메인 엔진 (FastAPI 요청용)
# =============================================================================
engine = create_async_engine(
url=db_settings.MYSQL_URL,
echo=False,
pool_size=20, # 기본 풀 크기: 20
max_overflow=20, # 추가 연결: 20 (총 최대 40)
pool_timeout=30, # 풀에서 연결 대기 시간 (초)
pool_recycle=280, # MySQL wait_timeout(기본 28800s, 클라우드는 보통 300s) 보다 짧게 설정
pool_pre_ping=True, # 연결 유효성 검사 (죽은 연결 자동 재연결)
pool_reset_on_return="rollback", # 반환 시 롤백으로 초기화
connect_args={
"connect_timeout": 10, # DB 연결 타임아웃
"charset": "utf8mb4",
},
)
# 메인 세션 팩토리 (FastAPI DI용)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False, # 명시적 flush 권장
)
# =============================================================================
# 백그라운드 태스크 전용 엔진 (메인 풀과 분리)
# =============================================================================
background_engine = create_async_engine(
url=db_settings.MYSQL_URL,
echo=False,
pool_size=10, # 백그라운드용 풀 크기: 10
max_overflow=10, # 추가 연결: 10 (총 최대 20)
pool_timeout=60, # 백그라운드는 대기 시간 여유있게
pool_recycle=280, # MySQL wait_timeout 보다 짧게 설정
pool_pre_ping=True, # 연결 유효성 검사 (죽은 연결 자동 재연결)
pool_reset_on_return="rollback",
connect_args={
"connect_timeout": 10,
"charset": "utf8mb4",
},
)
# 백그라운드 세션 팩토리
BackgroundSessionLocal = async_sessionmaker(
bind=background_engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def create_db_tables():
import asyncio
# 모델 import (테이블 메타데이터 등록용)
from app.home.models import Image, Project # noqa: F401
from app.lyric.models import Lyric # noqa: F401
from app.song.models import Song # noqa: F401
from app.video.models import Video # noqa: F401
print("Creating database tables...")
async with asyncio.timeout(10):
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
# FastAPI 의존성용 세션 제너레이터
async def get_session() -> AsyncGenerator[AsyncSession, None]:
start_time = time.perf_counter()
pool = engine.pool
# 커넥션 풀 상태 로깅 (디버깅용)
print(
f"[get_session] ACQUIRE - pool_size: {pool.size()}, "
f"in: {pool.checkedin()}, out: {pool.checkedout()}, "
f"overflow: {pool.overflow()}"
)
async with AsyncSessionLocal() as session:
acquire_time = time.perf_counter()
print(
f"[get_session] Session acquired in "
f"{(acquire_time - start_time)*1000:.1f}ms"
)
try:
yield session
except Exception as e:
await session.rollback()
print(
f"[get_session] ROLLBACK - error: {type(e).__name__}: {e}, "
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
)
raise e
finally:
total_time = time.perf_counter() - start_time
print(
f"[get_session] RELEASE - duration: {total_time*1000:.1f}ms, "
f"pool_out: {pool.checkedout()}"
)
# 백그라운드 태스크용 세션 제너레이터
async def get_background_session() -> AsyncGenerator[AsyncSession, None]:
start_time = time.perf_counter()
pool = background_engine.pool
print(
f"[get_background_session] ACQUIRE - pool_size: {pool.size()}, "
f"in: {pool.checkedin()}, out: {pool.checkedout()}, "
f"overflow: {pool.overflow()}"
)
async with BackgroundSessionLocal() as session:
acquire_time = time.perf_counter()
print(
f"[get_background_session] Session acquired in "
f"{(acquire_time - start_time)*1000:.1f}ms"
)
try:
yield session
except Exception as e:
await session.rollback()
print(
f"[get_background_session] ROLLBACK - "
f"error: {type(e).__name__}: {e}, "
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
)
raise e
finally:
total_time = time.perf_counter() - start_time
print(
f"[get_background_session] RELEASE - "
f"duration: {total_time*1000:.1f}ms, "
f"pool_out: {pool.checkedout()}"
)
# 앱 종료 시 엔진 리소스 정리 함수
async def dispose_engine() -> None:
print("[dispose_engine] Disposing database engines...")
await engine.dispose()
print("[dispose_engine] Main engine disposed")
await background_engine.dispose()
print("[dispose_engine] Background engine disposed - ALL DONE")
import time
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from config import db_settings
class Base(DeclarativeBase):
pass
# =============================================================================
# 메인 엔진 (FastAPI 요청용)
# =============================================================================
engine = create_async_engine(
url=db_settings.MYSQL_URL,
echo=False,
pool_size=20, # 기본 풀 크기: 20
max_overflow=20, # 추가 연결: 20 (총 최대 40)
pool_timeout=30, # 풀에서 연결 대기 시간 (초)
pool_recycle=280, # MySQL wait_timeout(기본 28800s, 클라우드는 보통 300s) 보다 짧게 설정
pool_pre_ping=True, # 연결 유효성 검사 (죽은 연결 자동 재연결)
pool_reset_on_return="rollback", # 반환 시 롤백으로 초기화
connect_args={
"connect_timeout": 10, # DB 연결 타임아웃
"charset": "utf8mb4",
},
)
# 메인 세션 팩토리 (FastAPI DI용)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False, # 명시적 flush 권장
)
# =============================================================================
# 백그라운드 태스크 전용 엔진 (메인 풀과 분리)
# =============================================================================
background_engine = create_async_engine(
url=db_settings.MYSQL_URL,
echo=False,
pool_size=10, # 백그라운드용 풀 크기: 10
max_overflow=10, # 추가 연결: 10 (총 최대 20)
pool_timeout=60, # 백그라운드는 대기 시간 여유있게
pool_recycle=280, # MySQL wait_timeout 보다 짧게 설정
pool_pre_ping=True, # 연결 유효성 검사 (죽은 연결 자동 재연결)
pool_reset_on_return="rollback",
connect_args={
"connect_timeout": 10,
"charset": "utf8mb4",
},
)
# 백그라운드 세션 팩토리
BackgroundSessionLocal = async_sessionmaker(
bind=background_engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def create_db_tables():
import asyncio
# 모델 import (테이블 메타데이터 등록용)
from app.home.models import Image, Project # noqa: F401
from app.lyric.models import Lyric # noqa: F401
from app.song.models import Song # noqa: F401
from app.video.models import Video # noqa: F401
print("Creating database tables...")
async with asyncio.timeout(10):
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
# FastAPI 의존성용 세션 제너레이터
async def get_session() -> AsyncGenerator[AsyncSession, None]:
start_time = time.perf_counter()
pool = engine.pool
# 커넥션 풀 상태 로깅 (디버깅용)
print(
f"[get_session] ACQUIRE - pool_size: {pool.size()}, "
f"in: {pool.checkedin()}, out: {pool.checkedout()}, "
f"overflow: {pool.overflow()}"
)
async with AsyncSessionLocal() as session:
acquire_time = time.perf_counter()
print(
f"[get_session] Session acquired in "
f"{(acquire_time - start_time)*1000:.1f}ms"
)
try:
yield session
except Exception as e:
await session.rollback()
print(
f"[get_session] ROLLBACK - error: {type(e).__name__}: {e}, "
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
)
raise e
finally:
total_time = time.perf_counter() - start_time
print(
f"[get_session] RELEASE - duration: {total_time*1000:.1f}ms, "
f"pool_out: {pool.checkedout()}"
)
# 백그라운드 태스크용 세션 제너레이터
async def get_background_session() -> AsyncGenerator[AsyncSession, None]:
start_time = time.perf_counter()
pool = background_engine.pool
print(
f"[get_background_session] ACQUIRE - pool_size: {pool.size()}, "
f"in: {pool.checkedin()}, out: {pool.checkedout()}, "
f"overflow: {pool.overflow()}"
)
async with BackgroundSessionLocal() as session:
acquire_time = time.perf_counter()
print(
f"[get_background_session] Session acquired in "
f"{(acquire_time - start_time)*1000:.1f}ms"
)
try:
yield session
except Exception as e:
await session.rollback()
print(
f"[get_background_session] ROLLBACK - "
f"error: {type(e).__name__}: {e}, "
f"duration: {(time.perf_counter() - start_time)*1000:.1f}ms"
)
raise e
finally:
total_time = time.perf_counter() - start_time
print(
f"[get_background_session] RELEASE - "
f"duration: {total_time*1000:.1f}ms, "
f"pool_out: {pool.checkedout()}"
)
# 앱 종료 시 엔진 리소스 정리 함수
async def dispose_engine() -> None:
print("[dispose_engine] Disposing database engines...")
await engine.dispose()
print("[dispose_engine] Main engine disposed")
await background_engine.dispose()
print("[dispose_engine] Background engine disposed - ALL DONE")