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:
@@ -208,6 +208,111 @@ async def safe_place_order(
|
||||
await _release_order_lock(stock_code, order_type)
|
||||
|
||||
|
||||
# ── [멀티테넌트 1단계 §5.8] 사용자 스코프 주문 락/래퍼 ────────────────────────
|
||||
# 기존 safe_place_order/_acquire_order_lock/_auto_cancel_if_pending는 시그니처
|
||||
# 불변 유지. 사용자별 계좌(ctx.kis)로 주문하는 경로는 아래 _v2 함수를 사용한다.
|
||||
async def _acquire_order_lock_v2(user_id, stock_code: str, order_type: str) -> bool:
|
||||
"""Redis 분산락 획득 — 사용자 네임스페이스 키(`order_lock:{user_id}:{code}:{type}`).
|
||||
|
||||
구조는 `_acquire_order_lock`과 동일(SETNX+TTL 60초). legacy 컨텍스트(user_id가
|
||||
None 또는 legacy owner id)도 이 함수를 쓰면 키에 user_id가 섞이므로, legacy
|
||||
경로는 기존 `_acquire_order_lock`(user_id 없는 키)을 그대로 사용해야 한다.
|
||||
"""
|
||||
try:
|
||||
from app.core.redis import get_redis
|
||||
client = get_redis()
|
||||
if not client:
|
||||
return True
|
||||
key = f"order_lock:{user_id}:{stock_code}:{order_type}"
|
||||
result = await client.set(key, "1", nx=True, ex=_ORDER_LOCK_TTL)
|
||||
return result is True
|
||||
except Exception as e:
|
||||
logger.debug(f"[order_lock_v2] user_id={user_id} 획득 오류 (패스): {e}")
|
||||
return True
|
||||
|
||||
|
||||
async def _release_order_lock_v2(user_id, stock_code: str, order_type: str) -> None:
|
||||
"""Redis 분산락 해제 — `_acquire_order_lock_v2`와 짝을 이루는 사용자 네임스페이스 키."""
|
||||
try:
|
||||
from app.core.redis import delete_key
|
||||
await delete_key(f"order_lock:{user_id}:{stock_code}:{order_type}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def safe_place_order_v2(
|
||||
ctx, # UserContext (순환 임포트 회피 — 타입은 app.services.tenant.context.UserContext)
|
||||
stock_code: str,
|
||||
order_type: str,
|
||||
quantity: int,
|
||||
price: float | None = None,
|
||||
is_domestic: bool = True,
|
||||
exchange_code: str = "NASD",
|
||||
) -> dict:
|
||||
"""`safe_place_order`의 사용자 스코프 버전 (설계 문서 §5.8).
|
||||
|
||||
- `ctx.is_legacy`면 기존 전역 경로(`_acquire_order_lock`/`_release_order_lock`,
|
||||
`_get_order_semaphore(stock_code)`)를 그대로 사용 — swing/daytrading exit_service
|
||||
등 기존 스케줄러가 잡는 락과 같은 키여야 같은 계좌·종목 동시 매도가 직렬화된다.
|
||||
사용자 컨텍스트(`is_legacy=False`)만 사용자 네임스페이스 키(`{user_id}:{code}`)를 쓴다.
|
||||
- 세마포어: `_get_order_semaphore(f"{ctx.user_id}:{stock_code}")` — 기존 함수 재사용,
|
||||
키 문자열만 사용자 네임스페이스로 바꿈(시그니처 불변).
|
||||
- Redis 락: `_acquire_order_lock_v2`/`_release_order_lock_v2` (legacy는 v1 그대로).
|
||||
- 주문 실행: `ctx.kis.place_order(...)`/`ctx.kis.place_overseas_order(...)`.
|
||||
- 반환 형식은 `safe_place_order`와 동일.
|
||||
"""
|
||||
if ctx.is_legacy:
|
||||
semaphore_key = stock_code
|
||||
lock_acquired = await _acquire_order_lock(stock_code, order_type)
|
||||
else:
|
||||
semaphore_key = f"{ctx.user_id}:{stock_code}"
|
||||
lock_acquired = await _acquire_order_lock_v2(ctx.user_id, stock_code, order_type)
|
||||
|
||||
if not lock_acquired:
|
||||
logger.warning(f"[SAFE_ORDER_V2] user_id={ctx.user_id} {stock_code} {order_type} — 분산락 획득 실패 (이미 처리 중)")
|
||||
return {"rt_cd": "-1", "msg1": "order_lock_busy"}
|
||||
|
||||
try:
|
||||
async with _get_order_semaphore(semaphore_key):
|
||||
if is_domestic:
|
||||
result = await ctx.kis.place_order(
|
||||
stock_code=stock_code,
|
||||
order_type=order_type,
|
||||
quantity=quantity,
|
||||
price=price,
|
||||
)
|
||||
else:
|
||||
result = await ctx.kis.place_overseas_order(
|
||||
symbol=stock_code,
|
||||
order_type=order_type,
|
||||
quantity=quantity,
|
||||
price=price or 0,
|
||||
exchange_code=exchange_code,
|
||||
)
|
||||
return result or {"rt_cd": "-1", "msg1": "no_response"}
|
||||
except Exception as e:
|
||||
logger.error(f"[SAFE_ORDER_V2] user_id={ctx.user_id} {stock_code} {order_type} 실패: {e}")
|
||||
return {"rt_cd": "-1", "msg1": str(e)}
|
||||
finally:
|
||||
if ctx.is_legacy:
|
||||
await _release_order_lock(stock_code, order_type)
|
||||
else:
|
||||
await _release_order_lock_v2(ctx.user_id, stock_code, order_type)
|
||||
|
||||
|
||||
async def _auto_cancel_if_pending_v2(ctx, order_id: str, stock_code: str, quantity: int, delay: int = 60) -> None:
|
||||
"""`_auto_cancel_if_pending`의 사용자 스코프 버전 — `ctx.kis.cancel_order`를 사용."""
|
||||
await asyncio.sleep(delay)
|
||||
try:
|
||||
result = await ctx.kis.cancel_order(order_id, quantity)
|
||||
if result.get("rt_cd") == "0":
|
||||
logger.info(f"[AUTO_CANCEL_V2] user_id={ctx.user_id} 미체결 자동 취소 완료: {stock_code} order_id={order_id}")
|
||||
else:
|
||||
logger.debug(f"[AUTO_CANCEL_V2] user_id={ctx.user_id} {stock_code} — {result.get('msg1')} (이미 체결됐을 수 있음)")
|
||||
except Exception as e:
|
||||
logger.debug(f"[AUTO_CANCEL_V2] user_id={ctx.user_id} {stock_code} — {type(e).__name__}: {e}")
|
||||
|
||||
|
||||
# ── 미체결 주문 1분 후 자동 취소 ─────────────────────────────────────────────
|
||||
async def _auto_cancel_if_pending(order_id: str, stock_code: str, quantity: int, delay: int = 60) -> None:
|
||||
"""delay초 후에도 PENDING 상태면 자동 취소.
|
||||
|
||||
Reference in New Issue
Block a user