refactor(lps): 설정을 TOML 단일 소스로 통합 — env/.env 이중 관리 제거
설정이 .env(compose 주입)·config.toml·코드 곳곳의 os.environ 직독 3계층에 흩어져 관리가 어려웠다. TOML 하나로 통합한다(협의 결정). - 신설 [WorkerConfig](동시성·폴백·프로필·데드라인·유예·Chrome·하트비트), [AlertConfig](웹훅·쿨다운·임계 10종). [WebServerConfig].api_keys(guard), [DecodoConfig].ip_request_budget/port_cooldown_sec 추가 — 흩어져 있던 LPS_* env 20여 개를 섹션으로 흡수. - server_configs 의 env override 계층(DB_*·시크릿·NAVER_KEYS 등) 삭제. 남는 env 는 APP_ENV(부트스트랩)·PROCESS_COUNT/WORKER_CONCURRENCY(실행 스크립트 대화형 입력 전용)·LPS_LIVE(테스트 옵트인)뿐. - Docker: env 주입 → config.docker.toml 마운트 + APP_ENV=docker. 이미지 무시크릿 유지, 마운트 누락 시 FileNotFoundError 즉시 실패. .env.example 삭제, config.docker.toml.example 신설. - negodata 호출부: guard 키를 env 직독에서 [WebServerConfig].lps_api_key (+기존 관례대로 env override)로 이동. - 실행 스크립트: 프로필·폴백·예산 프롬프트 제거(toml 소스 안내), 동시성/프로세스 수만 임시 override 로 유지. - docs 7종·example toml 의 env 표기를 toml 키로 일괄 갱신. - 전체 145 passed + APP_ENV=docker 로딩·API 기동 스모크 확인. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
993301be8b
commit
c81df5bd88
25 files changed
+308
-276
No files matched your search
@@ -2,46 +2,39 @@ import os
|
||||
|
||||
from config.config_loader import Configs
|
||||
from config.config_models import (
|
||||
WebServerConfig, LogConfig, MainDBConfig, NaverConfig, NaverKey, OpenAIConfig, DecodoConfig,
|
||||
WebServerConfig, LogConfig, MainDBConfig, NaverConfig, OpenAIConfig, DecodoConfig,
|
||||
WorkerConfig, AlertConfig,
|
||||
)
|
||||
|
||||
# 실행 환경 결정 (기본 local). 환경변수 APP_ENV 로 변경.
|
||||
# ── 설정 소스는 TOML 하나다(2026-07-13 협의 — env/.env 이중 관리 제거). ──
|
||||
# env 는 부트스트랩·실행 입력만 남는다:
|
||||
# APP_ENV : 어떤 toml 을 읽을지(local=호스트 실행 / docker=컨테이너에 마운트된 config.docker.toml)
|
||||
# PROCESS_COUNT : 실행 스크립트·부하벤치의 대화형 입력(uvicorn 워커 수 임시 override)
|
||||
# WORKER_CONCURRENCY : 워커 실행 스크립트의 대화형 입력(worker_main 이 읽음)
|
||||
# LPS_LIVE : 라이브 스모크 테스트 옵트인(설정이 아니라 실행 스위치)
|
||||
# 시크릿 포함 실값은 환경별 config.<APP_ENV>.toml(미커밋)에 두고, Docker 는 파일을 마운트한다.
|
||||
APP_ENV = os.environ.get("APP_ENV", "local")
|
||||
|
||||
_config_dir = os.path.dirname(__file__)
|
||||
_config_file = os.path.join(_config_dir, f"config.{APP_ENV}.toml")
|
||||
|
||||
# 운영 전제: 항상 APP_ENV=local 로 띄운다 → config.local.toml 사용 (test/docker 도 local 로 실행).
|
||||
if not os.path.exists(_config_file):
|
||||
raise FileNotFoundError(f"설정 파일이 없습니다: {_config_file} (APP_ENV={APP_ENV}). APP_ENV=local 로 실행하세요.")
|
||||
raise FileNotFoundError(
|
||||
f"설정 파일이 없습니다: {_config_file} (APP_ENV={APP_ENV}). "
|
||||
"호스트 실행은 config.local.toml 준비, 컨테이너는 config.docker.toml 마운트를 확인하세요."
|
||||
)
|
||||
|
||||
configs = Configs(_config_file)
|
||||
|
||||
web_server_config: WebServerConfig = configs.get(WebServerConfig)
|
||||
log_config: LogConfig = configs.get(LogConfig)
|
||||
main_db_config: MainDBConfig = configs.get(MainDBConfig)
|
||||
# 시크릿 포함 설정도 TOML 로 통합. 섹션이 없으면 기본값(빈/비활성).
|
||||
# 섹션이 없으면 기본값(빈/비활성)으로 동작.
|
||||
naver_config: NaverConfig = configs.get(NaverConfig) or NaverConfig()
|
||||
openai_config: OpenAIConfig = configs.get(OpenAIConfig) or OpenAIConfig()
|
||||
decodo_config: DecodoConfig = configs.get(DecodoConfig) or DecodoConfig()
|
||||
|
||||
|
||||
# DB 접속 env override (config.local.toml 유지, 도커에서 host 만 교체). 로컬은 env 미설정 → toml 그대로.
|
||||
def _apply_db_env_override(cfg: MainDBConfig):
|
||||
h = os.environ.get("DB_HOST")
|
||||
if h:
|
||||
cfg.write_host = cfg.read_host = h
|
||||
if os.environ.get("DB_PORT"):
|
||||
cfg.write_port = cfg.read_port = int(os.environ["DB_PORT"])
|
||||
if os.environ.get("DB_USER"):
|
||||
cfg.write_id = cfg.read_id = os.environ["DB_USER"]
|
||||
if os.environ.get("DB_PASSWORD"):
|
||||
cfg.write_pw = cfg.read_pw = os.environ["DB_PASSWORD"]
|
||||
if os.environ.get("DB_NAME"):
|
||||
cfg.name = os.environ["DB_NAME"]
|
||||
# 커넥션 예산 override (자동 산정용). env DB_CONNECTION_BUDGET.
|
||||
if os.environ.get("DB_CONNECTION_BUDGET"):
|
||||
cfg.connection_budget = int(os.environ["DB_CONNECTION_BUDGET"])
|
||||
worker_config: WorkerConfig = configs.get(WorkerConfig) or WorkerConfig()
|
||||
alert_config: AlertConfig = configs.get(AlertConfig) or AlertConfig()
|
||||
|
||||
|
||||
def _autosize_pool(cfg: MainDBConfig, process_count: int):
|
||||
@@ -66,49 +59,10 @@ def _autosize_pool(cfg: MainDBConfig, process_count: int):
|
||||
return cfg.pool_size, cfg.max_overflow
|
||||
|
||||
|
||||
def _apply_pool_env_override(cfg: MainDBConfig):
|
||||
"""명시적 풀 override — 자동 산정보다 우선(테스트·특수 배포용)."""
|
||||
if os.environ.get("DB_POOL_SIZE"):
|
||||
cfg.pool_size = int(os.environ["DB_POOL_SIZE"])
|
||||
if os.environ.get("DB_MAX_OVERFLOW"):
|
||||
cfg.max_overflow = int(os.environ["DB_MAX_OVERFLOW"])
|
||||
|
||||
|
||||
# 시크릿 env override — 프로덕션에선 API 키를 이미지에 굽지 않고 env(또는 시크릿매니저)로 주입한다.
|
||||
# 로컬은 env 미설정 → config.local.toml 값 그대로. (배포 시 toml 의 시크릿은 비워두고 아래 env 로 주입 권장)
|
||||
def _apply_secret_env_override():
|
||||
if os.environ.get("OPENAI_API_KEY"):
|
||||
openai_config.api_key = os.environ["OPENAI_API_KEY"]
|
||||
if os.environ.get("OPENAI_MODEL"):
|
||||
openai_config.model = os.environ["OPENAI_MODEL"]
|
||||
for k in ("host", "username", "password"):
|
||||
v = os.environ.get(f"DECODO_{k.upper()}")
|
||||
if v:
|
||||
setattr(decodo_config, k, v)
|
||||
# 포트 범위도 시크릿과 함께 env 주입 — example(플레이스홀더 0) 기반 이미지에서 이게 없으면
|
||||
# 자격증명을 넣어도 enabled=False(포트 0)로 프록시가 조용히 꺼진다.
|
||||
for k in ("port_start", "port_end", "session_minutes"):
|
||||
v = os.environ.get(f"DECODO_{k.upper()}")
|
||||
if v:
|
||||
setattr(decodo_config, k, int(v))
|
||||
if os.environ.get("DECODO_COST_PER_GB"):
|
||||
decodo_config.cost_per_gb = float(os.environ["DECODO_COST_PER_GB"])
|
||||
# NAVER_KEYS="id1:secret1,id2:secret2" 형식으로 키 로테이션 주입
|
||||
nk = os.environ.get("NAVER_KEYS")
|
||||
if nk:
|
||||
naver_config.keys = [NaverKey(id=i, secret=s)
|
||||
for i, s in (p.split(":", 1) for p in nk.split(",") if ":" in p)]
|
||||
|
||||
|
||||
_apply_db_env_override(main_db_config)
|
||||
_apply_secret_env_override()
|
||||
|
||||
# uvicorn 워커 수(멀티코어) env override — 부하테스트에서 1↔N 비교용(코드/toml 수정 없이).
|
||||
# uvicorn 워커 수 — 실행 스크립트/부하벤치의 대화형 입력만 env 로 임시 override(설정은 toml 이 소스).
|
||||
if os.environ.get("PROCESS_COUNT"):
|
||||
web_server_config.process_count = int(os.environ["PROCESS_COUNT"])
|
||||
|
||||
# 커넥션 풀 자동 산정: process_count(위에서 확정) 기준으로 예산 안에 맞춘다.
|
||||
# → 멀티워커 배포 시 풀 오버서브스크립션(→커넥션 고갈)을 config 가 스스로 방지.
|
||||
_pool_autosized = _autosize_pool(main_db_config, web_server_config.process_count)
|
||||
# 명시적 DB_POOL_SIZE/DB_MAX_OVERFLOW 는 자동 산정보다 우선(최종 override).
|
||||
_apply_pool_env_override(main_db_config)
|
||||
Reference in new issue
Block a user