feat: 멀티테넌트 1단계 — 사용자별 KIS 계좌·포트폴리오·수동매매 (MULTI_TENANT_ENABLED 기본 OFF)
설계: docs/multi_tenant_design.md / 검수: docs/multi_tenant_phase1_review.md (High 0, MT=False 배포 가능)
데이터·인프라
- user_kis_credentials(Fernet 암호화, PBKDF2 키 파생, key_version), stock_bans_v2 신설,
portfolio/trade_history/active_trades/trade_journals/trading_sessions 등 user_id nullable 추가
- alembic 0009~0011(idempotent, legacy owner 백필). main.py 기동 시 portfolio.user_id 스키마 검사(H1)
- Jenkinsfile: DB Migration 을 Deploy 앞으로, alembic 이력 없으면 stamp 0008 후 upgrade(N1)
- bootstrap: users 비어 있으면 BOOTSTRAP_ADMIN_* 로 관리자 시드 + .env KIS 자격증명 이관 + 백필(SAVEPOINT)
백엔드
- core/crypto.py, core/tenant_auth.py(get_current_user — 비활성 사용자 401, API 키→legacy owner,
deny_non_owner_session_when_mt), core/dt_utils.py
- services/tenant: context, kis_pool, registry(UserContextRegistry, 락 최소화·복호화 to_thread), risk_factory
- KoreaInvestmentAPI.for_user(사용자별 인스턴스, 토큰캐시 users/{id}/, 시세는 공용 위임)
- trade_executor.safe_place_order_v2(사용자별 락/세마포어, legacy ctx 는 기존 키)
- mdd_manager/loss_tracker _v2 + ban_until tz-aware/naive 경계 정규화(레거시 경로 버그 포함 수정)
- db_worker: payload user_id 옵션 필터, upsert_stock_ban_v2, legacy ActiveTrade 조회 LIMIT 1
- API: /account/credentials(등록·마스킹조회·삭제·연결테스트·자동매매), /auth/admin/tenant/*,
/portfolio/v2(조회·요약·sync·buy·sell), /trades/v2(+pending). PortfolioResponse Optional 수정
프론트
- /account 내 계좌 설정, useTenantMode(세션=v2 / API키=legacy, 미확정 시 쿼리·버튼 비활성),
계좌 미등록 인라인 안내, v2 매수/매도/거래이력 분기
테스트: tests/integration(격리 Postgres, KIS 전면 mock) 20 passed / 1 xfailed(0012 이전 제약)
2단계(스케줄러 사용자화·legacy 라우터 격리) 전까지 MULTI_TENANT_ENABLED=True 전환 금지
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
75
backend/app/services/tenant/kis_pool.py
Normal file
75
backend/app/services/tenant/kis_pool.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""사용자별 `KoreaInvestmentAPI` 인스턴스 풀 (설계 문서 §5.5).
|
||||
|
||||
- 자격증명 복호화는 호출 측(Registry/credentials API, B그룹)이 수행해
|
||||
평문(app_key/app_secret/account_no)을 넘겨준다 — 이 모듈은 DB 세션을 열지 않는다.
|
||||
- 캐시 키는 `user_id` 하나뿐이다(1단계는 사용자당 자격증명 1세트 전제, §3.1).
|
||||
자격증명이 바뀌면 호출 측이 반드시 `invalidate(user_id)`를 먼저 호출해야 한다
|
||||
(여기서는 캐시가 있으면 그대로 재사용 — 자격증명 변경 감지를 하지 않음).
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from app.services.korea_investment_api import KoreaInvestmentAPI
|
||||
from app.services import korea_investment_api as _kis_module
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KISClientPool:
|
||||
"""사용자별 `KoreaInvestmentAPI` 인스턴스 캐시 (asyncio.Lock으로 동시 생성 방지)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._instances: Dict[int, KoreaInvestmentAPI] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def get_or_create(
|
||||
self,
|
||||
user_id: int,
|
||||
app_key: str,
|
||||
app_secret: str,
|
||||
account_no: str,
|
||||
mode: str,
|
||||
) -> KoreaInvestmentAPI:
|
||||
"""캐시에 있으면 반환, 없으면 `KoreaInvestmentAPI.for_user(...)`로 생성 후 캐시."""
|
||||
existing = self._instances.get(user_id)
|
||||
if existing is not None:
|
||||
return existing
|
||||
async with self._lock:
|
||||
existing = self._instances.get(user_id)
|
||||
if existing is not None:
|
||||
return existing
|
||||
instance = KoreaInvestmentAPI.for_user(
|
||||
user_id=user_id,
|
||||
app_key=app_key,
|
||||
app_secret=app_secret,
|
||||
account_no=account_no,
|
||||
mode=mode,
|
||||
)
|
||||
self._instances[user_id] = instance
|
||||
return instance
|
||||
|
||||
async def invalidate(self, user_id: int) -> None:
|
||||
"""캐시된 인스턴스를 정리(httpx 클라이언트 close)하고 제거한다.
|
||||
|
||||
자격증명 교체/삭제 시 credentials API(B그룹)가 호출해야 한다.
|
||||
"""
|
||||
async with self._lock:
|
||||
instance = self._instances.pop(user_id, None)
|
||||
if instance is not None:
|
||||
try:
|
||||
await instance.close()
|
||||
except Exception as e:
|
||||
logger.warning("⚠️ KISClientPool.invalidate: user_id=%s close 실패: %s", user_id, e)
|
||||
|
||||
def get_legacy(self) -> KoreaInvestmentAPI:
|
||||
"""전역 legacy 싱글톤 반환 (`MULTI_TENANT_ENABLED=False` 또는 legacy owner 경로용)."""
|
||||
return _kis_module.korea_investment_api
|
||||
|
||||
def active_user_ids(self) -> list:
|
||||
"""현재 캐시된(생성된) 사용자 id 목록."""
|
||||
return list(self._instances.keys())
|
||||
|
||||
|
||||
# 모듈 싱글톤
|
||||
kis_client_pool = KISClientPool()
|
||||
Reference in New Issue
Block a user