Files
o2o-castad-backend/app/core/common.py
T

131 lines
5.7 KiB
Python

# app/main.py
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.utils.logger import get_logger
from app.utils.nvMapPwScraper import NvMapPwScraper
from config import p2v_settings, ssulbox_settings, traffic_settings
logger = get_logger("core")
#: 웹 프로세스 안에서 도는 썰박스 러너(SSULBOX_WORKER_ENABLED). 락을 잡은 워커 하나만 실제로 일한다
_ssul_stop: asyncio.Event = asyncio.Event()
_ssul_task: asyncio.Task | None = None
#: nginx 접근 로그 수집 루프(TRAFFIC_ACCESS_LOG_PATH 가 있을 때). 워커가 여럿이어도 커서 행 잠금으로 한 회차는 하나만 읽는다
_traffic_stop: asyncio.Event = asyncio.Event()
_traffic_task: asyncio.Task | None = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""FastAPI 애플리케이션 생명주기 관리"""
# Startup - 애플리케이션 시작 시
logger.info("Starting up...")
try:
from config import prj_settings
# DEBUG 모드일 때만 데이터베이스 테이블 자동 생성
if prj_settings.DEBUG:
from app.database.session import create_db_tables
await create_db_tables()
logger.info("Database tables created (DEBUG mode)")
# dashboard 테이블 초기화 및 기존 데이터 마이그레이션 (모든 환경)
from app.dashboard.migration import init_dashboard_table
await init_dashboard_table()
# 썰박스 스키마는 앱이 만들지 않는다 — **DB 변경은 전부 수동**이 방침이다.
# 배포 전에 docs/database-schema/migration_2026-07-30_ssulbox.sql 등을 직접 실행할 것.
# 썰박스 생성은 DB 대기열이다. 러너(단독 실행 락을 잡은 한 프로세스)가 queued 를 순서대로 가져가며,
# 기동 시 고아(running) 정리도 러너가 락을 잡은 뒤에만 한다 — 다른 프로세스의 정상 잡을 건드리지 않는다.
# 웹 워커가 여럿이면 SSULBOX_WORKER_ENABLED=false 로 끄고 전용 프로세스(worker/standalone.py)를 쓴다.
if ssulbox_settings.SSULBOX_ENABLED and ssulbox_settings.SSULBOX_WORKER_ENABLED:
from app.ssulbox.worker import runner as ssul_runner
global _ssul_stop, _ssul_task
_ssul_stop = asyncio.Event()
_ssul_task = asyncio.create_task(ssul_runner.run_forever(_ssul_stop), name="ssul-runner")
# 워커는 프로세스당 하나만 있어야 한다(같은 잡을 중복 집는다). gunicorn 워커가 여럿인
# 서버는 P2V_WORKER_ENABLED=false 로 이 경로를 끄고 standalone 프로세스를 따로 돌린다
if p2v_settings.P2V_ENABLED and p2v_settings.P2V_WORKER_ENABLED:
from app.p2v.worker import worker as p2v_worker
p2v_worker.start()
if traffic_settings.TRAFFIC_ACCESS_LOG_PATH:
from app.traffic.services import ingest_service
global _traffic_stop, _traffic_task
_traffic_stop = asyncio.Event()
_traffic_task = asyncio.create_task(ingest_service.run_forever(_traffic_stop), name="traffic-ingest")
await NvMapPwScraper.initiate_scraper()
except asyncio.TimeoutError:
logger.error("Database initialization timed out")
# 타임아웃 시 앱 시작 중단하려면 raise, 계속하려면 pass
raise
except Exception as e:
logger.error(f"Database initialization failed: {e}")
# 에러 시 앱 시작 중단하려면 raise, 계속하려면 pass
raise
yield # 애플리케이션 실행 중
# Shutdown - 애플리케이션 종료 시
logger.info("Shutting down...")
# 썰박스 러너 중단(락 해제 + 실행 중 생성 중단). dispose_engine() 전에 해야 러너가 죽은 커넥션에
# 접근하지 않는다. 대기 중인 잡은 DB 에 queued 로 남아 다음 러너가 이어서 처리하고, 실행 중이던 잡은
# 다음 러너가 기동하며 환불·정리한다.
if _ssul_task is not None:
try:
_ssul_stop.set()
await asyncio.wait_for(_ssul_task, timeout=20)
except Exception as e:
logger.warning(f"[ssulbox] 러너 종료 처리 실패: {e}")
_ssul_task.cancel()
# 접근 로그 수집 중단. 쓰던 회차는 커밋 전이면 롤백되고 다음 기동이 같은 커서 위치부터 다시 읽는다
if _traffic_task is not None:
try:
_traffic_stop.set()
await asyncio.wait_for(_traffic_task, timeout=10)
except Exception as e:
logger.warning(f"[traffic] 수집 루프 종료 처리 실패: {e}")
_traffic_task.cancel()
# P2V 워커 중단. 진행 중이던 잡은 다음 기동의 requeue_running 이 이어서 돌린다
if p2v_settings.P2V_ENABLED:
from app.p2v.utils import blob as p2v_blob
if p2v_settings.P2V_WORKER_ENABLED:
from app.p2v.worker import worker as p2v_worker
await p2v_worker.stop()
await p2v_blob.close_client()
# 공유 HTTP 클라이언트 종료
from app.utils.creatomate import close_shared_client
from app.utils.upload_blob_as_request import close_shared_blob_client
await close_shared_client()
await close_shared_blob_client()
from app.database.like_cache import close_like_cache
await close_like_cache()
# 데이터베이스 엔진 종료
from app.database.session import dispose_engine
await dispose_engine()
# FastAPI 앱 생성 (lifespan 적용)
app = FastAPI(title="CastAD", lifespan=lifespan)